0

If I handle it in the service (I assign the data to a property), the controller doesn't get the value when the data finally comes. If I respond with the promise itself it's ok, I can get the data from the controller. But what happens if there are more controllers that depend on the same service and I want that all of them get the latest data?

Is there a mechanism of notification to communicate from services to controllers?

Henry Morgan
  • 89
  • 1
  • 5
  • Just cache the promise in your service and return the promise if it exists otherwise do the $http. Then each controller gets notified. Or deep watch the data. – hassassin Feb 19 '15 at 00:03
  • Yes of course angularjs have two notification mechanism: broadcast and emit. for detail : you should visit https://docs.angularjs.org/api/ng/type/$rootScope.Scope – RockOnGom Feb 19 '15 at 00:04

1 Answers1

1

I suppose this is really a preference thing, because you can do either. I prefer to return the promise and deal with it in the controller, for the following reasons:

  1. Proper error handling if your call fails. You can handle a failing call in different ways, depending on which controller you're in.
  2. Consistency. You know that every time you use that service you'll get a promise back. This can be extended to your entire project too.

To solve your second problem, I think you have a few options. First, you can manage your scope hierarchy and use broadcasting or emitting to tell other child controllers about your data. You could do something like this in your controller:

myService.getData().success(function (data) {
  // do something with results
  $scope.$broadcast('GOT_DATA', data);
});

Then in a child/parent controller:

$scope.$on('GOT_DATA', function(event, data) {
  // use data in another controller
});

You could also consider caching the results in your service while also returning your promise. Then, whenever another controller calls that function, they get the same data as the previous call. This means you can inject your service into any controller you want, and then each of them can get data at different times but it will be the same as the original request.

Community
  • 1
  • 1
cjkenn
  • 186
  • 2
  • 6