0

有人可以向我解释一下吗:如果我从浏览器控制台中的集合中获取数据,它可以正常工作,但是在呈现模板(使用相同集合)的同时,它会抛出异常作为查询结果为空。我究竟做错了什么?

Hubs = new Meteor.Collection("hubs");
Meteor.subscribe("hubs");
Template.thread.posts = function() {
    var hubName = 'foo',
        thread = Session.get("currentThread"),
        hub = Hubs.find({ name: hubName }).fetch()[0];
//throws: "Uncaught TypeError: Cannot read property 'threads' of undefined "
    return hub.threads[thread].posts;
}

//this being executed in browser's console yeilds an object:
Hubs.find({name: 'foo'}).fetch()[0]

不过,使用相同集合的其他模板工作正常

4

1 回答 1

1

当 Meteor 最初在浏览器上加载时,它还没有来自服务器集合的数据。

它们需要很短的时间才能可用。所以你只需要处理没有提供结果的情况。当数据到达时,反应应该用新数据更新你的所有模板。

你可以使用类似的东西:

hub = Hubs.findOne({ name: hubName })
if(hub) return hub.threads[thread].posts;

findOnefind().fetch[0]. 因此,如果没有结果,即null没有返回任何内容,也.threads不会被读取,因此不会出现异常。

于 2013-04-20T16:13:25.030 回答