繁体   English   中英

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

[英]Iron Router: Pass data to client via meteor method

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

例:

流星法:

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

路由器:

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

        });
    }

流星方法返回正确的值,我可以在回调函数中访问该值。 但是我的问题是我不知道如何实际使用这些数据。 仅从回调返回它是行不通的。

什么是正确的方法? 还是在这种情况下调用Meteor方法根本不是个主意? 那有什么选择呢?

非常感谢您的回答!

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

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

但是,我认为最好的方法是将反应性优势与流星发布/订阅方法结合使用。 在下面的解决方案中,只要在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}}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM