subscribe

The subscribe method is part of the ReactiveContext, and available on every context and $scope.

The method expect the publication name (as defined in the server), function that return the arguments array, and result callback.

The second argument is a function, which returns an array of arguments as defined in the publication on the server side. Those arguments can be reactive with the help of getReactively and each change in these reactive variables will trigger the arguments method again and will update the subscription.

The third parameter is an optional callback which operator exactly like the callbacks in Meteor.subscribe.

The subscription will stop automatically when it's context ($scope) is destroyed.

Tip: You can just use the first argument, the rest is optional.


Arguments

Name Type Details Required
Publication name String The name of the publication, as defined in the server side using Meteor.publish. Yes
Arguments Function Function A function, which expected to return an array of arguments that will passed to the subscription. No
Result Callback Function
Object
May include onStop and onReady callbacks. If there is an error, it is passed as an argument to onStop. If a function is passed instead of an object, it is interpreted as an onReady callback. No

Return value

The method returns exactly the same parameters as Meteor.subscribe.


Usage Example:

myModule.controller('MyCtrl', ['$scope', '$reactive', function($scope, $reactive) {
  $reactive(this).attach($scope);

  this.subscribe('users');
}]);

Example with getReactively:

myModule.controller('MyCtrl', ['$scope', '$reactive', function($scope, $reactive) {
  $reactive(this).attach($scope);

  this.relevantId = 10;
  this.numberOfUsers = 3;

  this.subscribe('users', () => {
    return [ numberOfUsers, this.getReactively('relevantId') ];
  });

  this.relevantId = 50; // This will cause the subscribe arguments method to run again
  this.numberOfUsers = 5; // This won't cause the subscribe arguments method to run again
}]);

Example with subscription handle and callbacks:

myModule.controller('MyCtrl', ['$scope', '$reactive', function($scope, $reactive) {
  $reactive(this).attach($scope);

  this.numberOfParties = 3;

  var subscriptionHandle = this.subscribe('parties', () => [this.numberOfParties], {
    onReady: function () {
      console.log("onReady And the Items actually Arrive", arguments);
      subscriptionHandle.stop();  // Stopping the subscription, will cause onStop to fire
    },
    onStop: function (error) {
      if (error) {
        console.log('An error happened - ', error);
      } else {
        console.log('The subscription stopped');
      }
    }
  });

  console.log('subscription Handle',
    subscriptionHandle); // Will include subscriptionId, ready() and stop()

}]);