HttpClient and its benefits - amresh087/newronaRepos GitHub Wiki

  1. What is HttpClient and its benefits?

    Most of the Front-end applications communicate with backend services over HTTP protocol using either XMLHttpRequest interface or the fetch() API. Angular provides a simplified client HTTP API known as HttpClient which is based on top of XMLHttpRequest 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,

    1. Contains testability features
    2. Provides typed request and response objects
    3. Intercept request and response
    4. Supports Observable APIs
    5. Supports streamlined error handling
  2. Explain on how to use HttpClient with an example?

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

    1. Import HttpClient into root module:
      import { HttpClientModule } from '@angular/common/http';
      @NgModule({
        imports: [
          BrowserModule,
          // import HttpClientModule after BrowserModule.
          HttpClientModule,
        ],
        ......
        })
       export class AppModule {}
    2. 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);
        }
      }
    3. 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.

  3. How can you read full response?

    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 from HttpClient:

    getUserResponse(): Observable<HttpResponse<User>> {
      return this.http.get<User>(
        this.userUrl, { observe: 'response' });
    }

    Now HttpClient.get() method returns an Observable of typed HttpResponse rather than just the JSON data.

  4. How do you perform Error handling?

    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 passing error object as a second callback to subscribe() 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.

⚠️ **GitHub.com Fallback** ⚠️