How To use HttpClientModule in Angular 4+?

How To use HttpClientModule in Angular 4+?

The Web applications communicate with backend services over the HTTP/HTTPS protocol and the browsers support to the XMLHttpRequest interface and the fetch () API to execute HTTP request.

The new HttpClient service is included in the HttpClientModule and it used to initiate HTTP request and responses in angular apps.
ü  Stayed Informed -  HttpClientModule vs. HttpClient

The HttpClient is more modern and easy to use alternative of HTTP.
Also the HttpClient is use the XMLHttpRequest browser API to execute HTTP request and it specific the HTTP request type’s i.e.
ü  Get()
ü  Post()
ü  Put()
ü  Delete()
ü  Patch()
ü  Head()
ü  Jsonp()

HttpClientModule – NgModule which provides the HttpClient and associated with components services and the interceptors can be added to the chain behind HttpClient by binding them to the multi provider for HTTP_INTERCEPTORS.

The HttpClientModule imported form -
import { HttpClientModule } from '@angular/common/http';



Example for the get () and post () method on HttpClient –
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  baseUrl ="https://code-sample.com/";
  users = null;
 
 // Inject HttpClient into your component or service.
  constructor(private http: HttpClient){  }

  //Load User info.
  ngOnInit(): void {
     // Make the HTTP request:
    this.http.get(this.baseUrl +'api/users/').subscribe(data => {
      this.users = data;
    },
    err => {
      console.log("Error- something is wrong!")
    });   
  }

  addUser = function(){
    let user ={
      id: 1,
      name: 'Anil Singh',
      user_Id:9979,
      site : 'https://code-sample.com'
    }

    //Make the HTTP Post Request
    this.http.post(this.baseUrl +'api/addUser/', user)
        .subscribe(
          result => {
            console.log("The User added successfully!");
            console.log(result);
          },
          err => {
            console.log("Error- something is wrong!")
          });
  }
}

I hope you are enjoying with this post! Please share with you friends!! Thank you!!!
ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..

My Tech Blog - https://www.code-sample.com/
My Books - Book 1 and Book 2

How To use HttpClientModule in Angular 4+? How To use HttpClientModule in Angular 4+? Reviewed by Anil Singh on 3:34 AM Rating: (5)
www.code-sample.com/. Powered by Blogger.
^