In AngularJS, when designing services, it is well common to return an instance of the $http service. The code that requests it (usually within a controller), must process then the promise and do whatever it is to be done with the data that come from server.
Like in this example.
But, sometimes you just don’t want to handle the server information in the controller, because you might need to do it in many other places in your app, and you don’t want to repeat the same code in your controllers. After all, it seems reasonable that any processing related to your items (filters, date parsing or whatever you need to do) can be encapsulated in that ItemsService, so that you can reuse it easily.
Specially if it is something that must be done over and over, because the API you’re working with doesn’t exactly give you back what you need or in the format that you need.
On the other hand, you might want to reduce the number of http requests your app performs, and storing these data as a property of the service might be convenient.
Solution: the Observer Pattern
This is why I thought it could be a good idea to implement the observer pattern in angular services that retrieve information from server, store it and manipulate it in some way.
But if you want to implement this pattern in more than one service, it is better to define it just once and create a new service that inherits that pattern whenever necessary.
I’ve created a git repository with a complete working example. Next, I’ll describe briefly how it works.
The Observable Service (Parent)
First, a service is declared with the functions that implement the observable pattern. But instead of returning a JSON, as usual in an AngularJS service, we return a function:
Inheritable Service that Inherits the observableService
If you need to create a service that inherits from the observableService, that is also inheritable by other services, you should return a function, instead of a JSON object. This is what we do in basic-resource.js.
Controller that Observes Services that Inherit from observableService
Now that you have observable services, you can simply define the callbacks in your controllers, and these will be updated whenever the service retrieves new information.
We use analytics cookies, like those offered by Google Analytics, to help us understand things like how long a visitor stays on our website, what pages they find most useful, and how they arrived at our website. To learn more about Google Analytics and your data, visit this