这是我的问题: 我正在尝试在加载我的页面时加载一个实体进行API调用,将少数此实体属性保存到会话中 - 所以我基本上只进行一次调用,并在需要时使用属性。
但是当我尝试从路由中获取id参数时,我脚本开头的Router.current()
为空。
另一方面,当我在Router.current()
上拨打相同的helper
时,我可以获得我的参数。
知道出了什么问题/我怎样才能在调用helpers
之前获得此参数?
这是我的html,我将使用以下属性之一:
<input type="text" name="name" id="addCampaignInputName" value="{{currentCampaignName}}" placeholder="New Campaign Name">
和JS:
if (Meteor.isClient)
{
$(function () {
console.log( Router.current()); ==>> NULL
if( Router.current() !== null) {
Meteor.call("getApiCampaignsById", Router.current().params.id, function(error, results) {
Session.set('currentCampaignDetailsName', results.data.name);
Session.set('currentCampaignDetailsTrackingMethod', results.data.tracking_method_id);
Session.set('currentCampaignDetailsCampaignTypeId', results.data.campaign_type_id);
});
}
});
Template.addCampaign.helpers({
currentCampaignName: function() {
console.log( Router.current()); ===>> DUMP DATA
return Session.get('currentCampaignDetailsName');
},
});
}
答案 0 :(得分:3)
因为模板帮助程序总是在反应计算中运行,Router.current()
恰好是一个反应式数据源,所以当它准备就绪时,帮助程序将重新运行正确的值。< / p>
由于您正在使用iron:router
,因此可以使用onBeforeAction
hook,因为它们可以绑定到特定路由,并在路径参数可用时执行(使用this.params
)。
Router.route("/my-route", {
name: "myRoute",
onBeforeAction: function(){
Meteor.call("getApiCampaignsById", this.params.id, function(error, results) {
Session.set('currentCampaignDetailsName', results.data.name);
Session.set('currentCampaignDetailsTrackingMethod', results.data.tracking_method_id);
Session.set('currentCampaignDetailsCampaignTypeId', results.data.campaign_type_id);
});
//
this.next();
}
});
答案 1 :(得分:1)
只有在订阅/参数准备好后才应加载模板。 Look at my answer here,也许它可以解决您的问题(尤其是将参数附加到模板数据对象的部分。)
答案 2 :(得分:1)
您的第一个功能可能在加载任何其他内容之前在页面上运行,并且它不知道Router
是什么。在加载模板助手之前设置这些的最好方法是使用iron-router的onBeforeAction
钩子:
Router.route('/', {
name: 'home',
onBeforeAction: function() {
//set your session variables here
this.next();
}
});
这样,路由器应该加载已经设置了会话变量的页面。