0

首先,我使用的不是 Meteor 本身而是 Angular-Meteor,所以原理是一样的。我需要做的是在helper功能上验证资源是否有效,并根据其结果做出决定。

我认为findfindOne集合的功能在客户端是同步的,但似乎它们不是,或者我以错误的方式做事。

我有以下代码:

this.helpers({
      post() {
        let _post = Posts.findOne({
          _id: this.postId
        });

        if( typeof _post == 'undefined' )
          return this.$state.go('404');

        return _post;
      }
    });

this.postId来自 Url 参数。当我浏览应用程序时,一切正常。但是当我刷新页面时,this.postId被定义但Posts.find()返回undefined,显然,它进入 404 页面。

¿ 我该如何解决这种情况?

4

2 回答 2

1

这是因为当您刷新页面时,您的视图会在数据发送到客户端之前呈现。要解决此问题,您需要在检查数据是否存在之前确保数据已准备就绪。换句话说,就是检查你的订阅是否准备好了,用这段代码做个示范:

const handle = Meteor.subscribe('data');

if (handle.ready()) {
  const post = Posts.findOne(/**/);

  if (typeof post === 'undefined') {
    console.log('post does not exist');
  }
}
于 2017-01-21T09:56:11.687 回答
0

@Khang 关于在数据准备好之前呈现的视图是正确的。

另一种方法是使用反应变量this.getReactively()

这是您的助手的外观:

this.helpers({
  post() {
    let _post = Posts.findOne({
      _id: this.getReactively('postId')
    });

    if( typeof _post == 'undefined' )
      return this.$state.go('404');

    return _post;
  }
});

助手将第一次运行并且不返回任何内容(即在数据准备好之前),因此您的代码应该将其作为正常情况处理(不要这样做$state.go('404')

只要记住this.postId在你的构造函数中声明,否则getReactively()将不起作用。

于 2017-01-21T19:11:32.273 回答