【问题标题】:Iron-Router randomly returning undefined in MeteorIron-Router 在 Meteor 中随机返回 undefined
【发布时间】:2014-02-21 03:05:03
【问题描述】:

出于某种奇怪的原因,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});
    }
});

有时它会正常返回,而有时它只是返回 undefined。

这背后有什么原因吗?

【问题讨论】:

  • 我恐怕不明白:这里返回的undefined是什么?
  • 我的意思是 pollundefined 在 console.log(poll);这是 data : function () { .. } 下返回的内容
  • 使用 console.log 我可以看到由于某种原因它实际上是未定义的。
  • 这可能是因为来自订阅的数据尚未填充客户端的Polly 集合。将订阅上的wait设置为Polly,确保在处理路由之前为ready
  • 我没有设置任何订阅。我将如何设置等待?

标签: javascript meteor iron-router


【解决方案1】:

出现此问题的原因是,当路由执行时,Polly 集合有时已填充,而有时未填充。

这个问题可以通过在路由配置中显式使用waiting on a subscription 选项来防止waitOn


来自docs

默认情况下,新的 Meteor 应用程序包含 autopublish 和 insecure 包,它们共同模拟每个客户端对服务器数据库具有完全读/写访问权限的效果。这些是有用的原型设计工具,但通常不适合生产应用程序。准备好后,只需移除包即可。

要删除软件包,请致电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'); }
    // ...
});

【讨论】:

  • 由于某种原因这对我不起作用,在控制台中给我一个错误。 Uncaught TypeError: undefined is not a function这是我的代码:pastebin.com/bdS2xYwE
  • 您是在路由加载之后定义您的集合吗?它们应该位于在客户端和服务器上运行的单独文件中。此外,了解undefined 是什么会有所帮助。
  • route.js 文件既不在客户端目录中,也不在服务器目录中。它位于应用程序的主目录中。至于说什么是未定义的是这一行Polls = new Meteor.collection('polls_all'); 不知道出了什么问题。我在Meteor.subscribe('polls_all');上方有这一行@
  • 错误似乎是Meteor.collection() 的大写应该是Meteor.Collection() 解决了一个问题但是新错误是Exception from Deps recompute: Error: There is already a collection named 'polls_all' 这可能是因为我在waitOn 中有Meteor.subscribe然而,在之前的方法中,我不知道如何以任何其他方式访问该集合。集合本身也不正确。我只有一个 meteor.collection 对象。
  • 好的,我明白了,自动发布是为了原型设计(并且是为了方便)...但是有没有一种方法可以使用和不使用自动发布?
猜你喜欢
  • 2015-12-31
  • 2015-09-21
  • 1970-01-01
  • 2015-04-06
  • 2014-05-07
  • 2013-11-21
  • 1970-01-01
  • 2023-03-12
  • 1970-01-01
相关资源
最近更新 更多