铁路由器:通过流星方法将数据传递到客户端 [英] Iron Router: Pass data to client via meteor method

查看:86
本文介绍了铁路由器:通过流星方法将数据传递到客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序使用铁路由器:当用户点击包含通配符一定的路线,我想使用通配符的值来调用流星方法有它的返回值可以用来设置该数据上下文模板。

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.

例如:

流星方式:

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

路由器:

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? 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)
})

查看:

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

如果用户将改变他的名字,那么上面的方法将不会更新的userName ,直到用户再次开放的路线。

If user will change his name, then above method will not update userName until user open route again.

不过,我认为更好的方式去使用反应善良与流星的pub / sub方法。
在下面的解决方案的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.

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}}

这篇关于铁路由器:通过流星方法将数据传递到客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆