HttpClient and its benefits - amresh087/newronaRepos GitHub Wiki
-
Most of the Front-end applications communicate with backend services over
HTTP
protocol using eitherXMLHttpRequest
interface or thefetch()
API. Angular provides a simplified client HTTP API known asHttpClient
which is based on top ofXMLHttpRequest
interface. This client is available from@angular/common/http
package. You can import in your root module as below:import { HttpClientModule } from '@angular/common/http';
The major advantages of HttpClient can be listed as below,
- Contains testability features
- Provides typed request and response objects
- Intercept request and response
- Supports Observable APIs
- Supports streamlined error handling
-
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 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 injectsUserProfileService
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.
- Import
-
The response body doesn't or may not return full response data because sometimes servers also return special headers or status code, which are important for the application workflow. In order to get the full response, you should use
observe
option fromHttpClient
:getUserResponse(): Observable<HttpResponse<User>> { return this.http.get<User>( this.userUrl, { observe: 'response' }); }
Now
HttpClient.get()
method returns an Observable of typedHttpResponse
rather than just theJSON
data. -
If the request fails on the server or fails to reach the server due to network issues, then
HttpClient
will return an error object instead of a successful reponse. In this case, you need to handle in the component by passingerror
object as a second callback tosubscribe()
method.Let's see how it can be handled in the component with an example,
fetchUser() { this.userService.getProfile() .subscribe( (data: User) => this.userProfile = { ...data }, // success path error => this.error = error // error path ); }
It is always a good idea to give the user some meaningful feedback instead of displaying the raw error object returned from
HttpClient
.