Thursday 5 May 2016

Consuming a REST API with Angular2 Http-Service in Typescript


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

Angular Tutorial (Update to Angular 7)

As Angular 7 has just been released a few days ago. This tutorial is updated to show you how to create an Angular 7 project and the new fe...