Angular HttpClient get & post Request (GET & Post)

In this post, we will understand Angular HttpClient with example. When Angular version 4.3 launched, It gave us a new way to handle Http requests using the HttpClient library.

What is HttpClient in Angular?

HttpClient in Angular is a replacement of old Http library. It gives us some advance powerful feature like Http Interceptors to monitor or modify API requests or responses and ability to listen for progress events.

Prerequisite

Make sure you have running Angular 4.3 version or above to test the Angular HttpClient API or You can install Angular latest version by following our Angular installation guide.

Now you have a running angular project on your computer, So let’s install the Http Client Module.

Installing the new HttpClient Module

First, import the HttpClientModule from ‘@angular/common/http’ in your root app module file called app.module.ts.

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

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AddUserComponent } from './users/add-user/add-user.component';
import { ListUserComponent } from './users/list-user/list-user.component';
import { ConnectionStatusComponent } from './connection-status/connection-status.component';

import { HttpClientModule } from '@angular/common/http';

@NgModule({
    declarations: [
        AppComponent,
        AddUserComponent,
        ListUserComponent,
        ConnectionStatusComponent,
    ],
    imports: [
        BrowserModule,
        AppRoutingModule,
        HttpClientModule
    ],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule { }

Now you are ready to use HttpClient Module in your app.

To use it, create a service file and import as you do normally.

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

@Injectable({ providedIn: 'root' })

export class AppService {

    constructor(
        private http: HttpClient
    ) { }

    register(data: any) {
        // create a new user
    }

    get(id: any) {
        //get all users
    }
}

Basic Use of Angular HttpClient Module

The basic use of HttpClient Module is to make a GET, POST, PUT or DELETE requests from your app. Let’s see all the requests by example to understand how Angular HttpClient Module works.

Angular HttpClient GET Request- HttpClient.get():

To make Http GET request, HttpClient Module provides HttpClient.get method. It accepts two parameters, the First argument is API URL from where you want to fetch data and the second argument is optional.

If you keep the second argument blank, the response we receive from the server is a JSON object.

Let’s see the example code below.

export class AppService {
    
    constructor(
        private http: HttpClient
    ) { }

    //get all users
    getAll() {
        return this.http.get('http://localhost:3000/user/getAll', { responseType: 'text' } )
            .pipe(
                map(res => res),
                catchError((err) => this.handleError(err))
            )
    }

    private handleError(err: any) {
        return throwError(err || 'Server error');
    }
}

As said above by default GET request returns response in JSON format. But, If you want something else than JSON response, you can specify the expected response type as an object with responseType key.

I want the response from above code in ‘text’ format. So I have passed the second argument like this {responseType: 'text'}

Angular HttpClient POST Request- HttpClient.post():

Http POST request can be made by HttpClient.post method. It accepts three parameters, the First argument is API URL, the second argument is data (the data to POST in the body of the request) and the third argument is optional like HttpClient.get method.

See the example code below.

export class AppService {

    constructor(
        private http: HttpClient
        ) { }
    // create a new user
    create(data: any) {

        return this.http.post('http://localhost:3000/user/create', data)
            .pipe(
                map(res => res),
                catchError((err) => this.handleError(err))
            )
    }

    private handleError(err: any) {
        return throwError(err || 'Server error');
    }

}

Angular HttpClient PUT request- HttpClient.put():

To perform a PUT request we simply called the HttpClient.put method.

Suppose you want to update a user record from user table then you need to use PUT request. It accepts three parameters similar to the HTTP POST request.

export class AppService {

    constructor(
        private http: HttpClient
    ) { }
    // Update user
    update(data: any) {
        return this.http.put('http://localhost:3000/user/update/' + data.userId, data)
            .pipe(
                map(res => res),
                catchError((err) => this.handleError(err))
            )
    }
    private handleError(err: any) {
        return throwError(err || 'Server error');
    }

}

In the above code, we have used only two arguments because as above said the last parameter is optional and can be left blank.

Angular HttpClient DELETE request- HttpClient.delete():

To perform a DELETE request we simply use HttpClient.delete method. The format of this method is exactly the same as the HttpClient.get method.

export class AppService {

    constructor(
        private http: HttpClient
    ) { }

    //delete a user
    delete(id: any) {
        return this.http.delete('http://localhost:3000/user/delete/' + id);
    }
    private handleError(err: any) {
        return throwError(err || 'Server error');
    }
}

In the above code, I have used only one argument URL because as I told above the last parameter is optional and can be left empty or can be set expected ResponseType.

you can find the detailed explanation on HttpClient requests and different type of argument options here.

Leave a Reply