2016-04-02 98 views
1

我正在尝试访问(另一)用户在流星客户端的详细信息。我有一个称为'userDetails'的服务器端方法,我从名为'acc'的模板助手调用。流星:在客户端访问用户详细信息

服务器方法:

'userDetails': function(userId) { 
     check(userId, String); 
     return Meteor.users.findOne({_id: userId}, 
            {fields: { 
            "services.facebook.first_name": 1, 
            "profile.birthday": 1, 
            "services.facebook.gender": 1, 
            "profile.location.name": 1 
            }}); 
    } 

模板帮手:

acc: function(_id) { 
    Meteor.call('userDetails', _id, function(err, res) { 
     if(err) throw error; 
     return res; 
    }); 
    } 

当我尝试在模板中访问acc.profile.birthday我没有得到任何东西。什么会造成这种情况?

+0

你不能像这样访问模板助手。您必须在模板中使用'acc'来查看输出。 –

+0

Hi @BlazeSahlzen,你是说我不能在模板中使用{{acc.profile.birthday}}?因为那就是我正在做的... – L4zl0w

+1

哦,对不起,我误解了。是的,你可以这么做。您可以在返回之前尝试安装res对象,以确保对象具有什么结构。 –

回答

2

流星调用是异步调用,这就是为什么你的帮助器没有返回任何数据。

最佳选择这里是要么使用SessionReactiveVarReactiveDict

我将在这里使用

acc: function(_id) { 
    Meteor.call('userDetails', _id, function(err, res) { 
    if(err){ 

    }else{ 
     Session.set('userDetails', res) 
    } 

    }); 
    return Session.get('userDetails') 
} 

Session选项在你的HTML你可以使用这个助手这样

{{#if acc}} 
    {{name}} 
    ... 
{{else}} 
    <p>Information not found</p> 
{{/if}} 
+1

“return”语句是否不在Method方法调用之外? –

+1

是的,现在改变它 – Sasikanth

+1

谢谢,我设法使它与这种方法一起工作。 – L4zl0w

2

你必须在else语句中包装返回值。

if(error) { 

} 
else { 
    return res; 
} 

异步调用方法。这意味着回调函数将在您的服务器方法完成时执行。

如果你希望显示模板的结果,你有两种可能性:

1 /使用会话。

acc: function(_id) { 
    Meteor.call('userDetails', _id, function(err, res) { 
    if(err){ 
    }else{ 
     Session.set('data', res) 
    } 

    }); 
    return Session.get('data') 
} 

2 /使用模板订阅(更好的解决方案): 在服务器上,你发布的数据:

Meteor.publish("data", function(){ 
    return Meteor.users.findOne(...) 
}); 

在客户端,你订阅:

Template.mytemplate.onCreated(function() { 
    Template.instance().subscribe("data"); 
}); 

然后直接在客户端上,您将能够创建一个帮助程序并调用findOne。

在HTML:

{{#if Template.subscriptionsReady}} 
    {{#each myHelper}} 
     {{acc.profile.birthday}} 
    {{/each}} 
    {{else}} 
    <p>Loading...</p> 
    {{/if}} 

关于用户的重要通知: 用户配置文件默认情况下编辑。请阅读:https://dweldon.silvrback.com/common-mistakes

+0

Thanks @hlx,这是一个很好而全面的答案,但是我不确定我是否有第二个帮手来返回会话。 – L4zl0w

+0

@ L4zl0w我更新了答案,所以你不需要第二个帮手。请标记答案,以免问题不再出现 – hlx

相关问题