An example dataservice to call your favourite API.
Configuration
Its always a good thing if you have your configuration seperated stored anywhere in your application. I always go for a file like “app.constants.ts” where I store all my values. If anything changes there, like a version of the api which is stored in the url or the endpoint/server whatever, I can do those changes immediatelly at one point.
Notice the injectable attribute to generate the metadata to make the service available through DI in other modules.
You can read more about DI in anuglar 2 in this blog post Dependency Injection in Angular 2
Now we have this going we can generate our service:
The Service
First of all you have to create a module which only contains a service which is only responsible for calling an API with a specific endpoint.
This dataservice gets the configuration we just did and the HTTP-Service via DI. We included it over the new module-loading-syntax. Also notice the typed items we included and the configuration we have to pull in to make it available.
It is also important to tell the http-calls which header to use. “Application/Json” in this case.
Now you can include, inject and use this service to make http-calls to your API like this:
I think this should be basically it. Pay attention to the typed answer you get from the service
and to the subsribe after calling the “GetAll”-Method from the service.
No comments:
Post a Comment