[英]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.