Fetch data with the new HttpClient on Angular 5

 

Notegiven the semver adopted from now on by Angular team, I will refer to all versions of Angular2+ as Angular. For the old Angular 1.x, I will use AngularJs

The new HttpClient on Angular 5 is here to replace the deprecating @angular/http module.

The new HttpClientModule will be imported from @angular/common/http.

For the purpose of this article, we are going to use a service to fetch the data in which we are going to inject the new HttpClient. Our service is going to be injected into the component that is supposed to consume the data.

First, we need to import the HttpClientModule. We need to do this only once at the app.module level.

After that, we are going to inject the HttpClient into our service and to use it inside a get() function.

The getUser() will return an Observable that we are going to treat in our consuming component.

Since getUsers() returns an Observable, we call the subscribe() function to listen and process the returned data.

 

If your company needs consulting on migration from Angular 1 to Angular 2/4/5 or training/update Angular knowledge, write me to contact@bogdancarpean.com

Leave a Reply

Your email address will not be published. Required fields are marked *