【问题标题】:Iron Router: Pass data to client via meteor methodIron Router:通过流星方法将数据传递给客户端
【发布时间】:2014-09-12 20:38:12
【问题描述】:

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

例子:

流星法:

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

路由器:

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

        });
    }

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

这样做的正确方法是什么?或者在这种情况下调用 Meteor 方法根本不是一个好主意?那还有什么办法呢?

非常感谢您的回答!

【问题讨论】:

    标签: javascript asynchronous meteor iron-router


    【解决方案1】:

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

    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,直到用户再次打开路由。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-06
      • 1970-01-01
      • 2017-04-02
      • 2015-06-02
      相关资源
      最近更新 更多