What is Angular HttpClient with Example?

HttpClient in Angular


I am Going to explain HttpClient in angular but below are the main questions we have to know before jump into this Topic.  

  1. What is Angular HttpClient?
  2. What are the Various requests with Angular HttpClient?
  3. What are the advantages of HttpClient?
  4. Simple CRUD Operations in Angular

What is Angular HttpClient?

  • Angular HttpClient is used to performing the HTTP requests and responses
  • Angular HttpClient service is available in The @angular/common/http package
  • New HttpClient service is included in the HTTP Client module which is used to initiate HTTP requests and responses in Angular Apps.
  • The HttpClientModule needs to import into the module level. usually in the app module
  • Angular HttpClient also gives other useful functionality like headers and Interceptors etc.


What are the different methods available in Angular HttpClient?

Below are the HttpClient Methods available

      • get()
      • post()
      • put()
      • delete()
      • head()
      • patch()
      • options()
      • jsonp()

What are the Advantages of Angular HttpClient?

  • It includes Observable APIs.
  • It can have the HTTP Headers in Options
  • It includes the high testability features
  • It includes typed request
  • It includes response objects
  • It includes request and response interception
  • It includes error handling


Simple CRUD operations Using Angular HttpClient Module?

Below is the TypeScript code for simple CRUD operation by using HTTP Verbs. in this example I have used only 4 Verbs. the Verbs are Get(), Put(), Post, and Delete()


import { Injectable } from '@angular/core';
import { FormBuilderValidators } from '@angular/forms';
import { HttpClientHttpHeaders } from '@angular/common/http';
import { UserModel } from '../models/userModel';
import { Observable } from 'rxjs';
import { forEach } from '@angular/router/src/utils/collection';
import { RegisterDropDownddl } from '../models/appConstantUsage';

@Injectable({
   providedIn: 'root'
})
export class UserService {
constructor(private _httpHttpClient ) { }
   readonly baseURIstring = 'http://localhost:21124/api';

userProfileAdd(formData) {
     return this._http.post(this.baseURI + '/UserProfile'formData);
   }
   userProfile() {
     return this._http.get(this.baseURI + '/UserProfile');
   }
  userDelete(userId) {
     return this._http.delete(this.baseURI + '/UserProfile',userId);
   }
  userUpdate(formData) {
     return this._http.put(this.baseURI + '/UserProfile',formData);
   }



Conclusion

Angular HttpClient is one of the great topics. it has some other important classes like HttpHeaders and HttpParams. If you like this article please do share and like this article.



No comments: