Search code examples
javascriptmeteoriron-router

Router doesn't wait for subscription


My problem is that I have two similar paths and in first one router waits for my subscriptions and renders whole template, but the second one is rendering right away with no loading and data passed is causing errors(since there is no collection subscribed yet). I paste my code here, the second one is different because of template and data passed but the rest is practically the same. I'm just starting with iron-routing, maybe someone can tell me where is mistake?

Router.map(function() {
        this.route('/', {
            onBeforeAction: function() {
                if (Meteor.user()) {
                    if (Meteor.user().firstLogin)
                        this.render("firstLogin");
                    else
                        Router.go('/news');
                } else {
                    this.render("start");
                }
            },
            waitOn: function() {
                return Meteor.subscribe('allUsers');
            },
            onAfterAction: function() {
                document.title = "someTitle";
            },
            loadingTemplate: "loading",
        });
        this.route('users',{
            path:'/user/:_id',
            layoutTemplate: 'secondLayout',
            yieldTemplates: {
                'template1': {to: 'center' },
                'template2': {to: 'top' },
                'template3': {to: 'left' },
                'template4': {to: 'right' },
            },
            waitOn: function(){
                return Meteor.subscribe("allUsers");
            },
            data: function(){
                return Meteor.users.findOne({_id:String(this.params._id)});
            },
            loadingTemplate: "loading",
        });
    });

Solution

  • You are using iron-router in the lagacy. If you're just starting it. I recommend you use the new api. In that case, you can use this.ready() to check the subscription is finished or not

    Following is the example from the official guide

    Router.route('/post/:_id', function () {
      // add the subscription handle to our waitlist
      this.wait(Meteor.subscribe('item', this.params._id));
    
      // this.ready() is true if all items in the wait list are ready
    
      if (this.ready()) {
        this.render();
      } else {
        this.render('Loading');
      }
    });