[英]Why am I getting an 'undefined' error but the code is working in my Meteor template?
I made this UI.registerHelper: 我做了这个UI.registerHelper:
UI.registerHelper('addressCityName', function(id) {
"use strict";
return Cities.findOne({_id: id }).name
})
This allows me to access the name
property of the linked city
id in my Addresses collection. 这使我可以访问“地址”集合中链接的city
ID的name
属性。
It works in the browser, but in the console I get an error that says: Exception in template helper: TypeError: Cannot read property 'name' of undefined
. 它可以在浏览器中工作,但是在控制台中我收到一条错误消息: Exception in template helper: TypeError: Cannot read property 'name' of undefined
。
If I remove the name
property from the UI.registerHelper return value, the error goes away but the browser no longer shows the city name. 如果我从UI.registerHelper返回值中删除了name
属性,则错误消失了,但浏览器不再显示城市名称。
What is up with this and how can I fix it? 这是怎么回事,我该如何解决?
When you try to get the name using Cities.findOne({_id: id }).name
. 当您尝试使用Cities.findOne({_id: id }).name
。 But your subscription was not ready on client side. 但是您的订阅尚未在客户端准备好。 So the output of Cities.findOne({_id: id })
is undefined. 因此Cities.findOne({_id: id })
是不确定的。
So if your try to get Cities.findOne({_id: id }).name
so if you visualize your output will be like undefined.name
. 因此,如果您尝试获取Cities.findOne({_id: id }).name
那么如果您将其可视化,输出将类似于undefined.name
。 So this is the reason you are getting the error. 因此,这就是您收到错误的原因。
To solving the issue you can add a if condition and it will solve the issue. 要解决该问题,您可以添加一个if条件,它将解决该问题。
UI.registerHelper('addressCityName', function(id) {
"use strict";
if(Cities.findOne({_id: id })) {
return Cities.findOne({_id: id }).name
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.