How To Send AJAX Request in Angular is today’s topic. Right now, the latest version of Angular framework is Angular 8.

If you are new to Angular 8, then check out my Angular 8 Tutorial in this blog. Most front-end applications communicate with the backend services over an HTTP protocol. Modern browsers support the two different APIs for making HTTP requests.
XMLHttpRequest interface and the fetch() API.
We will use XMLHttpRequest for Angular application.

Content Overview

  • 1 Angular 8 HttpClient Example
  • 2 Angular HTTP module
  • 3 Setup Angular 8 Project
  • 4 Import HttpClientModule
  • 5 Create Service File
  • 6 Create a backend Server
  • 7 Send AJAX request to the server in Angular
  • 8 HTTP Headers
  • 9 HTTP PUT request in Angular
  • 10 HTTP PATCH request in Angular
  • 11 HTTP DELETE request in Angular
  • 12 HTTP POST request in Angular

Angular 8 HttpClient Example

The HttpClient in @angular/common/Http offers the simplified client HTTP API for Angular applications that rests on a XMLHttpRequest interface exposed by browsers. Additional benefits of the HttpClient include testability features, typed request and response objects, request and response interception, Observable apis, and streamlined error handling.

Angular HTTP module

The Angular HTTP module all have the **RxJS **Observable-based API. What this means is that the multiple calls to the HTTP module will all return the observable, that we need to subscribe to one way or the other way.

Here are some key points to bear in mind that a particular type of Observables returned by an HTTP module.
If we don’t subscribe to the observables, nothing will happen.If we subscribe the multiple times to these observables, multiple HTTP requests will be triggered (see this post for more details).This particular type of Observables are the single-value streams: If an HTTP request is successful, these observables will emit only one value and then complete.These observables will emit the error if the HTTP request fails, more on this later.## Setup Angular 8 Project

We have already set up an Angular CLI, and now we need to create a project using the following command.

ng new ng8crud

It will create a new project and install the required files to set up the boilerplate.

Import HttpClientModule

Before you can use a HttpClient, you need to import an Angular HttpClientModule. Most apps do import in the root AppModule.

// app.module.ts

import { NgModule }         from '@angular/core';
import { BrowserModule }    from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
    BrowserModule,
    // import HttpClientModule after BrowserModule.
    HttpClientModule,
  ],
  declarations: [
    AppComponent,
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule {}

Create Service File

In Angular application, it is a best practice to create a service file related to a particular module.

If an angular app needs to interact with the back end server, then we can write the API calling code inside the service file.

So, if we need to send a POST request to the server, then we import the HttpClient inside the service file and make an AJAX request to the server with the data object. After a successful request, the server sends a response back to the client.

You typically post-process the data, add the error handling logic, and maybe some retry logic to cope with an intermittent connectivity.

The component quickly becomes cluttered with the data access. The component becomes harder to understand, even harder to test, and the data access logic can’t be re-used or standardized.

That’s why it is the best practice to separate presentation of the data from data access by encapsulating the data access in the separate service and delegating to that service in a component.

So, now create a service file by the following command.

ng g s config

Now, write the following code inside the config.service.ts file.

// config.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class ConfigService {
  constructor(private http: HttpClient) { }
}

Create a backend Server

We need the fake data to work with and that is why I am using one package called json-server** **for this tutorial. Okay, so let us install the package using the Yarn package manager.

yarn global add json-server

# or

npm install -g json-server

Now we need to create the folder inside **src directory **called **data **and in that folder, create one file called db.json. Let us add the following data inside the **db.json **file.

{
    "characters": [
    {
        "id": "1",
        "name": "Peter Dinklage",
        "age": "45"
    },
    {
        "id": "2",
        "name": "Lina Heady",
        "age": "43"
    },
    {
        "id": "3",
        "name": "Emilia Clarke",
        "age": "30"
    },
    {
        "id": "4",
        "name": "Kit Harrington",
        "age": "30"
    },
    {
        "id": "5",
        "name": "Sean Bean",
        "age": "50"
    }]
}

Now, start the JSON server using the following command.

json-server --watch src/data/db.json --port 4000

Now, we have the server running that can feed our data to our React Bootstrap Application.

Our JSON server is started at port: 4000 and URL is http://localhost:4000/characters.

Send AJAX request to the server in Angular

We have created a backend server and also created a service file.

Now, we need to write the code that sends a GET request to the json server.

So, write the following code inside the **config.service.ts **file.

// config.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class ConfigService {
  constructor(private http: HttpClient) { }
  url = 'http://localhost:4000';
  getCharacters() {
    return this
            .http
            .get(`${this.url}/characters`);
  }
}

And here is the example of a small service that queries the database above using an HTTP GET, and fetch the data. This data then goes to the related component and using HTML, and we can show the data on the screen.

The above example is using the HTTP module in a small service file, that is displaying a list of characters. Let’s break down the following example step-by-step:
We are using the new HttpClient client module, and injecting it in the constructor/Then we are calling the get() method, which is returning the data.
The HttpClient.get() method parsed a JSON server response into an anonymous Object type. It doesn’t know what a shape or attributes of that object is.

You can tell the HttpClient the type of response to make consuming the output easier and more prominent.

First, define the interface with the Characters attribute.

export interface Characters {
    id: Number;
    name: String;
    age: Number;
}

Then, specify that interface as an HttpClient.get() call’s type parameter in the service.

HTTP Headers

If we want to add the custom HTTP Headers in our HTTP request then, in addition to the headers the browser already attaches automatically. We can do this by using the HttpHeaders class.

const headers = new HttpHeaders()
            .set("X-CustomHeader", "custom header value");

getCharacters() { 
   return this 
          .http
          .get(`${this.url}/characters`, {headers}); }

As we can see, HttpHeaders also has an immutable API, and we are passing a configuration object as the second argument of the get() call.

This configuration object only has one property named headers, just like the local const that we defined – so we used the object short-hand creation notation to describe the configuration object.

HTTP PUT request in Angular

Just like in the case of GET request, we can also use the Angular HTTP Client to do all the other available HTTP methods, namely the methods typically used for data modification such as PUT.

The PUT method should only be used if we want to replace the value of the resource.

HTTP PATCH request in Angular

Most often than not, instead of providing the complete new version of the resource, what we want to do is to update a single property. And this is the primary use case for the use of the HTTP PATCHmethod.

The PATCH request is useful in situations where there is some further server-side modification of the patched values, such for example via a database trigger or a Firebase rule.

HTTP DELETE request in Angular

Another frequent operation that we want to do is to trigger the logical delete of some data. This operation can completely wipe the data from our database or mark some data as deleted.

HTTP POST request in Angular

If the operation that we are trying to do does not fit the description of any of the methods above (GET, PUT, PATCH, DELETE), then we can use an HTTP wildcard modification operation: POST.

That operation is typically used to add the new data to the database, although there are many other use cases.

Finally, Angular 8 HttpClient Example | How To Send AJAX Request in Angular is over.

#angular #web-development #ajax

Angular 8 HttpClient Example | How To Send AJAX Request In Angular
4 Likes815.10 GEEK