出于某种奇怪的原因,iron-router
随机返回 undefined。
this.route('pollyShow', {
path: '/polly/:_id',
template: 'polly_show',
notFoundTemplate: 'notFound',
before: function () {
var id = this.params._id;
var poll = Polls.findOne({_id: id});
console.log(poll);
var ip_array = poll.already_voted;
$.getJSON("http://smart-ip.net/geoip-json?callback=?", function(data){
ip_voted = ip_array.indexOf(data.host);
if (ip_voted > -1) {
Router.go('pollyResults', {_id: id});
}
});
},
data: function() {
return Polls.findOne({_id: this.params._id});
}
});
有时它正常返回,而其他时候它只是返回未定义。
这背后有什么原因吗?
最佳答案
出现此问题的原因是 Polly
当路由执行时,集合有时会被填充,有时则不会填充。
可以通过显式 waiting on a subscription
来防止此问题使用waitOn
路由配置中的选项。
来自docs :
By default, a new Meteor app includes the autopublish and insecure packages, which together mimic the effect of each client having full read/write access to the server's database. These are useful prototyping tools, but typically not appropriate for production applications. When you're ready, just remove the packages.
要删除软件包,请调用meteor remove <package-name>
.
然后您需要在服务器上显式发布您希望在客户端上看到的记录:
server/publications.js:
Meteor.publish('all_of_polly', function () { return Polls.find({}); });
并在客户端订阅:
this.route('pollyShow', {
path: '/polly/:_id',
template: 'polly_show',
notFoundTemplate: 'notFound',
waitOn: function () { return Meteor.subscribe('all_of_polly'); }
// ...
});
关于javascript - Iron-Router 在 Meteor 中随机返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21915122/