CREATING THE BASE STORE
Since we can have more than one http-store in our application (for example, to-do’s & users) we want to create a base store so that we can reuse the functionality. Create a new Angular service with the following contents. I will go through each section of the code seperately to explain the function of the code (the full service can be found on my gitub):
There is only one real requirement on our entities, they must have an ID. This is so that we can keep track of the entities we have and ensures we can edit and remove the intended entity.
What follows is the definition of the
entities$ member. This is an RxJS observable. This object is our single source of truth for everyone that decides to listen (
subscribe) to our updates. This object holds all of our entities and can only be modified from within the service, making the data flow unidirectional.
The next property is a somewhat strange object, a RxJS BehaviorSubject. This object allows us to provide updates (via
.next()) to the
entities$ observable. This is private so that we don’t expose the update functionality to the outside world and thus keeping control over the observable. We connect these two properties in the
The two functions further down are the modifiers of the
entities$ observable, the so-called
Below that is a generic
get function that makes a call to the backend and updates the
entities$ object with the newly retrieved data.
What else can we add?
We can provide much more functionality within our service, like:
event messages (like ‘successful get request’);
get an item from the cache;
update an item in the cache;
add an item to the cache;
find and item in the cache;
Remove an item from the cache;
A config object with url’s so that we won’t have to feed it an url for every request we make;
and much more.
If we start expanding this service we might even separate the functionality into two different classes, an
entity-store, which contains the
entities$ object and the reducers and the
http-store that extends from the entity-store, which contains all the default calls (
delete) to the backend.
But for this turorial we’ll keep it to this simple implementation, since it is enough to support our example.