Angular question detail
Explain on how to use `HttpClient` with an example?
Below are the steps need to be followed for the usage of HttpClient.
- Import
HttpClientinto root module:
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
BrowserModule,
// import HttpClientModule after BrowserModule.
HttpClientModule,
],
......
})
export class AppModule {}
- Inject the
HttpClientinto the application: Let's create a userProfileService(userprofile.service.ts) as an example. It also defines get method ofHttpClient:
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 injectsUserProfileServiceand 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.