如何在 Template.rendered 中访问 Meteor 中 nvd3 的订阅

How to Access subscription in Template.rendered for nvd3 in Meteor

我想用一个简单的 nvd3 discrete bar chart 显示来自 collection 的数据。

当我用本地 collection 尝试时,它工作得很好。 现在我将相同的数据转移到数据库 collection 但我无法在 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 甚至 up-to-date 还是已弃用?

提前致谢!

手筒

我认为这里的问题是混淆了订阅和获取的自动运行:

自动运行是运行当数据改变时,所以需要在自动运行内部的不是订阅,而是数据查找。

试试这个:

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() 部分 'should' 在自动运行中是反应性的,但我不是 100% 确定。