Explain on how to use HttpClient with an example?
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 inject 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.
April 14, 2022
438
Read more
What is Angular Framework?
November 04, 2022
AngularWhat is a Angular module?
November 03, 2022
AngularWhat are the steps to use animation module?
October 31, 2022
Angular