How to Use HttpClient Module and Service to Send Ajax/Http Requests in Angular 9?


Could you explain step by step how to use HttpClient module and service to send Ajax/Http requests to backend servers in Angular 9?

February 27, 2020

HttpClient is an inbuilt  module that is used to send request from the client side to the server and fetch the response to the request.

Steps In Angular 9  to send Http Request

  1. Create your Angular project using  command “ng new <project name>”
  2. HttpClient  module is already included when an angular application is created. We just need to include this in app. Open and edit src/app/app.module.ts  file of the app then add this  import HttpModule which is the part of ‘@angular/common/http’ .  Before using a HttpClient, we need to import an Angular HttpClientModule in import section of app.module .ts file. Now Angular HttpClient is reday to use or inject with  the service.
  3.  Create a Service File using command “ng generate service <filename> ” or “ng g s <filename>”. Service File will have code lines:  import the ClientModule into the file and provide an instance for the httpClient in the constructor.
  4. Now we create a Fake Server from where data for the request will be fetched, to fetch this fake data  I am using one package called json-serverand we can install this pakage by using command “npm install -g jason server” this command hast to be run inside the present application.
  5. Now we need to create the folder inside src directory called data and in that folder, create one file called <filename>.json
  6. Now we create data inside this json file and that data can contain properties and their values.We need to write the code that sends a GET request to the json server, and we write this in the service.ts file. code goes like this:
    export class filename {
      constructor(private http: HttpClient) { } // instance for HttpClient
      url = 'http://localhost:4000';
      getCharacters() {
        return this
  7. So this is thexample of small service that queries the dtabase in using get() method and fetch the data. This data goes to the related component and using HTML, we can show the dta on screen.

I hope this helps. thank you







Skip to toolbar