我想用一个简单的nvd3离散条形图显示集合中的数据。
当我在当地的一个收藏品中试用时,效果很好。现在我将相同的数据转移到数据库集合中,但我无法在Meteor.rendered.中获取数据
Template.chartPopularWordsAll.onCreated(() => {
let template = Template.instance();
template.autorun(() => {
template.subscribe('dataViewed'); // DataViewed.find()
});
Template.chartPopularWordsAll.rendered = function() {
let data = DataViewed.find({}, {
limit: 5,
sort: {
timesViewed: -1
}
}).fetch();
console.log(data); // <-- this returns an empty array
}
问题:如何访问.rendered中的数据?
在Meteor文档中,搜索".rendered"没有得到任何结果,我只能找到.onRendered。.rendered是最新的还是不推荐使用?
提前感谢!
Muff
我认为这里的问题是混合了订阅和获取的自动运行:
autorun是在数据更改时运行的,因此不需要订阅,而是需要数据查找。
试试这个:
Template.chartPopularWordsAll.onCreated(() => {
let template = Template.instance();
template.subscribe('dataViewed'); // DataViewed.find()
});
Template.chartPopularWordsAll.rendered = function() {
template.autorun(() => {
let data = DataViewed.find({}, {
limit: 5,
sort: {
timesViewed: -1
}
}).fetch();
console.log(data); //
}
}
如果这不起作用,请尝试不在对数据的调用中提取,而是在需要数据时提取:Collection.find()会给你一个游标,它是被动的,但一旦提取,你就会得到一个数组,它不是被动的。Collection.find()部分"应该"在autorun中是被动的,但我不能100%确定。