Meteor:访问客户端上的用户详细信息



我正在尝试访问流星客户端上(另一个)用户的详细信息。我有一个名为"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.e寿辰时,我什么也得不到。是什么原因造成的?

Meteor调用是异步调用,这就是帮助程序不返回任何数据的原因。

这里的最佳选择是使用SessionReactiveVarReactiveDict

我将在这里使用Session选项

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

在你的html中,你可以像一样使用这个助手

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

您必须将返回封装在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

相关内容

最新更新