当尝试读取属性时,meter在浏览器控制台中给我一个TypeError: Cannot read property 'featuredImage' of undefined
错误。但它读取featuredImage
,网站运行良好。我怎样才能消除这个错误?这是因为我的订阅还没有准备好吗?是这样的吗?如何解决?(附言:我正在使用流路由器,所以我等不及在路由器中订阅了)
我的模板代码:
Template.About.helpers({
page: () => {
return findPage();
},
featuredImage: () => {
var thisPage = findPage();
return Images.findOne({
"_id": thisPage.featuredImage
});
}
});
function findPage() {
return Pages.findOne({
slug: 'about'
});
}
路由器代码:
FlowRouter.route('/about', {
name: 'about',
subscriptions: function() {
this.register('page', Meteor.subscribe('pages', 'about'));
this.register('image', Meteor.subscribe('images'));
},
action() {
BlazeLayout.render('MainLayout', {
content: 'About'
});
setTitle('About Us');
},
fastRender: true
});
订阅可能还没有准备好。FlowRouter提供了一个处理此问题的实用程序,您的助手应该如下所示:
Template.About.helpers({
page: () => {
// If you only need a specific subscription to be ready
return FlowRouter.subsReady('page') && findPage() || null;
},
featuredImage: () => {
// Ensure ALL subscriptions are ready
if ( FlowRouter.subsReady() ) {
var thisPage = findPage();
return Images.findOne({
"_id": thisPage.featuredImage // Probably should be thisPage.featuredImage._id
});
}
return null;
}
});
但是,为了获得最大性能,您应该使用if (FlowRouter.subsReady('page') && Flowrouter.subsReady('image'))
而不是FlowRouter.subsReady()
,因为如果您有其他较大的挂起订阅,即使您不需要它们,它也会等待这些订阅。