铁路由器语法:onAfterAction

iron router syntax: onAfterAction

Router.route('/courses/:_catalog', function () {
  var courseCatalog = this.params._catalog.toUpperCase();

  Meteor.subscribe("courseCatalog", courseCatalog);

  this.render('CourseDetail', {
    to: 'content',
    data: function () {
      return Courses.findOne({catalog: courseCatalog});
    }
  });
}, {
  onAfterAction: function() {
    if (!Meteor.isClient) {
      return;
    }
    debugger
    var course = this.data(); <======
    SEO.set({
      title: "course.catalog"
    });
  }
});

在上面的代码中,请看debugger语句。我想访问数据,但似乎我做错了什么,因为 this.data 不存在。我也试过 Courses.find().fetch() 但我只在 onAfterAction 中得到一个空数组。什么是正确的语法,我错过了什么?

您需要先订阅数据。查看 waitOn 函数来执行此操作。服务器只发送您订阅的文档,由于您没有订阅,Courses.find().fetch() returns 一个空数组。

此外,不要将 SEO 内容放在 onAfterAction 中。放在 onRun 中,保证只会 运行 一次。

它需要在 this.ready() 块内:

  onAfterAction: function() {
    if (this.ready()) {
      var course = this.data(); 
      ...
    }
  }