Maximus S
Maximus S

Reputation: 11135

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"
    });
  }
});

In the above code, please look at the debugger statement. I want to access the data but it seems I am doing something wrong because this.data doesn't exist. I also tried Courses.find().fetch() but I only get an empty array inside onAfterAction. What's the right syntax and what am I missing?

Upvotes: 2

Views: 941

Answers (2)

FreePender
FreePender

Reputation: 4879

It needs to be inside a this.ready() block:

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

Upvotes: 2

Elie Steinbock
Elie Steinbock

Reputation: 5098

You need to subscribe to data first. Have a look at the waitOn function to do this. The server only sends the documents you subscribed to, and since you didn't subscribe, Courses.find().fetch() returns an empty array.

Also, don't put SEO stuff in onAfterAction. Put it in onRun which is guaranteed to only run once.

Upvotes: 0

Related Questions