Question

Is there a way to extend an object returned by an Angular Service, Factory, or Provider with event pub/sub?

I'd like to do something like:

angular.module('app').factory('user', function(Event){
  var user = {
    // User methods...
  };
  return angular.extend(user, Event);
})

// In a distant time and place...
angular.module('app').directive('nav', function(user){
  scope: true,
  templateUrl: 'something',
  link: function(scope){
    user.on('logIn', function(user){
      scope.user = user
    })
  }
})

I accomplished something similar with promises. That is usually a good way to communicate asynchronously out of a service, but a user can log out and in, and promises only resolve once. Events are a better fit here.

I also understand I could solve this by broadcasting/emiting on $rootScope and listening on scope, but I think that is smelly. :)

What kinds of things patterns have you guys come up with to mediate between services?

Was it helpful?

Solution

I'm use (a modified version of) a pubsub service that you can check out here.

You can read about the trade offs for $rootScope events and pubsub with this question

Hope this helped

OTHER TIPS

I was looking at this same problem. Particularly how to allow services to broadcast and subscribe to events without accessing $rootScope (bad for a few reasons). I utilized the very excellent js-signals implementation from here : http://millermedeiros.github.io/js-signals/ and wrapped it into an angular service.

github gist here : https://gist.github.com/anonymous/b552c7fafa77427e6d06

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top