+1 vote
in Angular by

Explain on how to use HttpClient with an example?

1 Answer

0 votes
by

Below are the steps need to be followed for the usage of HttpClient.

Import HttpClient into root module:

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

@NgModule({

  imports: [

    BrowserModule,

    // import HttpClientModule after BrowserModule.

    HttpClientModule,

  ],

  ......

  })

 export class AppModule {}

Inject the HttpClient into the application: Let's create a userProfileService(userprofile.service.ts) as an example. It also defines get method of HttpClient:

import { Injectable } from '@angular/core';

import { HttpClient } from '@angular/common/http';

const userProfileUrl: string = 'assets/data/profile.json';

@Injectable()

export class UserProfileService {

  constructor(private http: HttpClient) { }

  getUserProfile() {

    return this.http.get(this.userProfileUrl);

  }

}

Create a component for subscribing service: Let's create a component called UserProfileComponent(userprofile.component.ts), which injects UserProfileService and invokes the service method:

fetchUserProfile() {

  this.userProfileService.getUserProfile()

    .subscribe((data: User) => this.user = {

        id: data['userId'],

        name: data['firstName'],

        city:  data['city']

    });

}

Since the above service method returns an Observable which needs to be subscribed in the component.

...