Search code examples
meteoriron-router

what is the difference of subscribing collection under waitOn , subscriptions and onBeforeAction


I would like to the difference if any in the following ways of subscribing data,

using waitOn

waitOn:function(){
  Meteor.subscribe('//some published function)
 }

using onBeforeAction

Router.onBeforeAction : function(){
   Meteor.subscribe('//some published function)
 }

using subscriptions

subscriptions: function() {
    this.subscribe('items');
   }

Solution

  • If you want to publish data only for authorized users, it is possible that you check (if user is authenticated) for a route, in onBeforeAction. Something like:

    Router.map(function(){
    
      this.route('home', {
        path : '/',
        template : 'home'
      });
    
      this.route('register', {
        path : '/register',
        template : 'register'
      });
    
      this.route('login', {
        path : '/login',
        template : 'login'
      });
    
      this.route('requestlisting', {
        path : '/requestlisting',
        template : 'requestlisting',
        waitOn : function(){
            return Meteor.subscribe('RequestsPublication');
        }
      });
      ...
    });
    
    var requireLogin = function () {
       if(!Meteor.user()){
           if(Meteor.loggingIn()){
              this.render(this.loadingTemplate);
           }else{
              Router.go('login');
           }
       } else {
           this.next();
       }
    }
    
    Router.onBeforeAction(requireLogin, {only: ['requestlisting',...]});
    

    In this example, in onBeforeAction, routing occurs for 'requestlisting' only if a user logged in, after then it makes sense to subscribe to any data.