Reputation: 40215
I have two services which fetch two different kinds of data from my server. Each of those has two controllers which $scope.$watch
that data for changes.
I wanted to get smart and detect loss/re-gain of internet connection, so I added an app.service('internetConnectionAvailableService'
. When one of my data fetch services detects an HTTP result, it informs the "internetConnectionAvailableService" of success or failure.
I would like the other data fetch service to be aware of that.
I suppose that I could just lump both data fetch service into one & drop the internetConnectionAvailableService, but I would rather not (what if I end up with more data fetch services?).
So, I figure it's either broadcast
/ $on
or use a $watch
. Google seems to recommend using a $watch
, but I can't seem to get it work in my data fetch service ....
app.service('GetServerDataService',function(){
var serverData;
return {
getServerData: function()
{
return serverData;
},
$scope.$watch(internetConnectionAvailableService.isInternetConnectionAvailable,
function(){
}
}
}
gives "Uncaught SyntaxError: Unexpected token . "
I am very new to Angular, so had a wild guess at using $rootscope.$watch
instead, but that gives me the same message.
What am I doing wrong? How to I watch another service's data? Or should I use broadcast
instead?
I think I could have phrased this better and asked "How do communicate between two services?"
Upvotes: 3
Views: 250
Reputation: 10276
EDIT:
It seems you want to communicate between services. You can indeed use $rootScope broadcast, which will trigger a broadcast storm along all your controllers and watches. A more object-oriented approach is to create a PubSub service which your services can inject and use. See also this question:
What's the correct way to communicate between controllers in AngularJS?
Upvotes: 2