[英]Meteor.user().profile only defined after a page refresh
我有一个名为“ isActive”的助手和一个名为“ create”的模板。
Template.create.isActive = function () {
return Meteor.user().profile.isActive;
};
当我尝试运行此代码时,它将在控制台中返回以下内容:“模板助手中的异常:TypeError:无法读取未定义的属性'profile'”。
我通过使用铁路由器来等待配置文件加载来解决此问题:
//startup on server side:
Meteor.publish("userData", function() {
if (this.userId) {
return Meteor.users.find({_id: this.userId},
{fields: {'profile.isActive': 1}});
} else {
this.ready();
}
});
//startup on client side
Meteor.subscribe('userData');
//router
this.route('create', {
path: 'create',
waitOn : function () {
return Meteor.subscribe('userData');
},
data : function () {
return Meteor.users.findOne({_id: this.params._id});
},
action : function () {
if (this.ready()) {
this.render();
}
}
});
但是...仅在刷新页面时有效,而在初始加载时不起作用。 有人知道为什么会这样吗? 有解决方法或更好的方法吗?
为了避免错误“模板帮助器中的异常:TypeError:无法读取未定义的属性'profile'”,您需要检查Meteor.user()
是否返回了对象。 标准模式是:
Template.create.isActive = function () {
var user = Meteor.user();
return user && user.profle.isActive;
};
一旦您的助手抛出错误,反应性将不起作用,因此您需要确保处理订阅数据尚未到达的情况。
同样,等待“ userData”订阅将延迟模板加载,但用户配置文件在登录时会自动发布(作为空订阅)。 因此,您的等待会导致任意延迟,这将增加Meteor.user()定义的机会,但它不会直接等待所需的数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.