Alex Langberg
Alex Langberg

Reputation: 163

Angular service using $watch to do $http call when a property is changed

I'm pretty new to Angular and wondering what the best way to handle this is. My app is structured with a service that keeps track of the app state and currently loaded data. I inject this into all my controllers so the app state will be shared with them and can also be changed between controllers by using the service. The service is outlined a bit like this:

app.factory('AppStateService', function() {
  return {
    selected_section: "blog",
    data_of_selected_section: {here_comes_data_from_an_api}
  }
}

As said, I inject this in all my controllers and bind them to the controller scope, so they can all change those properties and this works perfectly. However, I'd really like the service to automatically do an $http call to an API, whenever some of the properties change. When the data comes back from the API, I want this data assigned to a property so the controllers can update based on this data.

In the above example for instance, if a controller changes selected_section from e.g. "blog" to "main", I want the service to do the $http call and put the returned data in data_of_selected_section to let it propagate to the controllers. I could of course do this directly from the controller and push the result to the service from there, but then I'd have to replicate that code in each controller. Thus, I'd rather want the service to do it by itself.

What is the best way to do this? I guess I'll have to build in a $watch or $watchCollection somewhere in the service but I have a hard time wrapping my head around exactly how to do so. Especially since I could easily imagine that doing it the wrong way could kill performance.

On a side note, the reason I want to do it this way is because I'm doing data visualization and thus it is mostly my interface and not my data that will change. Thus, I'd really like to store my data and app state "globally" in a service. I don't know if it makes sense. Any help would be greatly appreciated!

Upvotes: 1

Views: 209

Answers (1)

BKM
BKM

Reputation: 7079

You could use .run as this method will instantiate the service on every route change.

app.run(function ($rootScope, AppStateService) {
    $rootScope.$on('$routeChangeStart', function () {
       $rootScope.data = AppStateService.data_of_selected_section
    });
});

You can write your http call inside the service as it will be automatically called whenever there is a change in the route

Upvotes: 1

Related Questions