简体   繁体   English

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

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

My application uses iron router: When a user hits a certain route that contains a wildcard, I would like to use the value of the wildcard to call a meteor method and have its return value be used to set the data context for the template. 我的应用程序使用铁路由器:当用户点击包含通配符的特定路由时,我想使用通配符的值来调用流星方法,并使用其返回值来设置模板的数据上下文。

Example: 例:

Meteor method: 流星法:

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

Router: 路由器:

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

        });
    }

The meteor method returns the correct value and I can access that value in the callback function. 流星方法返回正确的值,我可以在回调函数中访问该值。 But my problem is that I don't know how to actually use that data. 但是我的问题是我不知道如何实际使用这些数据。 Just returning it from the callback doesn't work. 仅从回调返回它是行不通的。

What is the right way to do this? 什么是正确的方法? Or is it not a got idea at all to call a Meteor method in this case? 还是在这种情况下调用Meteor方法根本不是个主意? What is the alternative then? 那有什么选择呢?

Thank you very much for your answers! 非常感谢您的回答!

You can update view using this approach : 您可以使用以下方法更新视图:

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

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

View: 视图:

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

If user will change his name, then above method will not update userName until user open route again. 如果用户将更改其名称,则上述方法在用户再次打开路由之前不会更新userName

However I think the better way to go is using reactivity goodness with meteor pub/sub methodology. 但是,我认为最好的方法是将反应性优势与流星发布/订阅方法结合使用。 In below solution userName will be updated on view whenever it will change in mongo. 在下面的解决方案中,只要在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
      }
   }
})

And on server: 在服务器上:

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

In template someRoute you display userName by typing: 在模板someRoute ,通过键入以下内容显示userName

{{userName}}

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

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