在我收到此错误之前,我遇到了类似的问题:
模板助手中的异常:TypeError:无法读取未定义的属性"profile"
同样的事情再次发生,但是在第二个订单上,其中包含另一个用户配置文件信息(定义了第一个配置文件).我如何让它在{{#each orders}}中重新渲染?
当只有2个订单时,由于某种原因,似乎info.firstName,lastName和building被调用了3次...
在HTML中:
<template name="orderItem">
<section>
<form role="form" id="ordersList">
<div>
{{#each orders}}
<input type="text" name="name" value="{{info.firstName}} {{info.lastName}}">
{{/each}}
</div>
<div>
{{#each orders}}
<input type="text" name="building" value={{info.building}}>
{{/each}}
</div>
<div>
{{#each orders}}
<input type="text" name="featuredDish" value={{featuredDish}}>
{{/each}}
</div>
</form>
</section>
</template>
Run Code Online (Sandbox Code Playgroud)
在javascript中:
Template.orderItem.orders = function() {
var todaysDate = new Date();
return Orders.find({dateOrdered: {"$gte": todaysDate}});
};
Template.orderItem.info = function() {
var userId = this.userId;
var user = Meteor.users.findOne(userId)
var firstName = user.profile.firstName;
var lastName = user.profile.lastName;
var building = user.profile.building;
return {
firstName: firstName,
lastName: lastName,
building: building
}
};
Run Code Online (Sandbox Code Playgroud)
感谢帮助!
Kub*_*bek 15
此错误是常见问题.您正在尝试访问未定义的用户对象.函数info不检查user对象是否正确.使用称为守卫的技术:
Template.orderItem.info = function() {
var userId = this.userId;
var user = Meteor.users.findOne(userId)
var firstName = user && user.profile && user.profile.firstName;
var lastName = user && user.profile && user.profile.lastName;
var building = user && user.profile && user.profile.building;
return {
firstName: firstName,
lastName: lastName,
building: building
}
};
Run Code Online (Sandbox Code Playgroud)
即使用户,上面的代码也不会抛出任何错误undefined.
我假设你已经删除了autopublish包裹.可能你还没有发布/订阅Meteor.users集合,所以没有数据可以在minimongo中找到.
记得发布Meteor.users集合并订阅它:
Meteor.publish("users", function(){
return Meteor.users.find({},{fields:{profile:1}})
})
Meteor.subscribe("users");
Run Code Online (Sandbox Code Playgroud)
发布Meteor.users的某些信息以及Meteor.user的更多信息