简体   繁体   中英

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? 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.

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

And on server:

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

In template someRoute you display userName by typing:

{{userName}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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