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.

...
import { HttpClientModule } from '@angular/common/http';

...
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    ...,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

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

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable()
export class FetchDataService {

  constructor(private _http: HttpClient) { }

  getUsers() {
    return this._http.get('https://yourapi/users');
  }

}

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

import { Component, OnInit } from '@angular/core';
import { FetchDataService } from '../fetch-data.service';

@Component({
  selector: 'fetch-data',
  templateUrl: './fetch-data.component.html',
  styleUrls: ['./fetch-data.component.scss']
})
export class FetchDataComponent implements OnInit {

  constructor(private _fetchDataService: FetchDataService) { }

  data: any; //any here is just for demo purpose; please change with the type returned by your endpoint

  ngOnInit() {
     this._fetchDataService.getUsers().subscribe(
      data => { this.data = data},
      err => console.error(err)
     );
  }

}

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 *