铁路由器:通过流星方法将数据传递给客户端

时间:2014-09-12 20:38:12

标签: javascript asynchronous meteor iron-router

我的应用程序使用铁路由器:当用户点击包含通配符的某个路由时,我想使用通配符的值来调用流星方法,并使用其返回值来设置数据上下文。模板。

示例:

流星法:

getUserName: function(id){
    return Meteor.users.findOne({_id: id}).profile.name;
}

路由器:

data: function(){
        Meteor.call('getUserName', this.params.userId, function(error, result){

        });
    }

meteor方法返回正确的值,我可以在回调函数中访问该值。但我的问题是我不知道如何实际使用这些数据。只是从回调中返回它并不起作用。

这样做的正确方法是什么?或者在这种情况下调用Meteor方法根本不是一个想法?那么替代方案是什么?

非常感谢您的回答!

1 个答案:

答案 0 :(得分:2)

您可以使用以下方法更新视图:

Meteor.call("getUserName",this.params.userId,  function(error,result){
  if(error)  {
    throw new Error("Cannot get userName");
    return;      
  }

  Session.set("userName",result)
})

查看:

Template.template_name.helpers({
  userName:function(){
    return Session.get("userName");
  }
})

如果用户将更改其名称,则上述方法将不会更新userName,直到用户再次打开路线。

然而,我认为更好的方法是使用流星pub / sub方法的反应性良好。 在下面的解决方案中,只要在mongo中更改,userName将在视图中更新。

Router.onBeforeAction('loading');

this.route("someRoute", {
   waitOn:function(){
     return Meteor.subscribe("getUser",this.params.userId);
   },
   data:function(){
      var user = Meteor.users.findOne({_id: this.params.userId});
      var userName = user && user.profile && user.profile.name;
      return{
        userName: userName
      }
   }
})

在服务器上:

Meteor.publish("getUser",function(userId){
  return Meteor.users.find(userId,{fields:{profile:1}});
})

在模板someRoute中,您可以输入以下内容显示userName

{{userName}}