Introduction to Angular’s New HttpClient

204
SHARES
929
VIEWS

Angular 4.3 brings us a new easier and better way to handle http requests with the HttpClient library. HttpClient also gives us advanced functionality like the ability to listen for progress events and interceptors to monitor or modify requests or responses.

Basic Installation & Setup

Open app.module.ts

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

import { AppComponent } from './app.component';

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    HttpClientModule // add HttpClientModule in imports
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

And now we can use HttpClient into our App

data.service.ts

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

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

  // ......
}

Basic Usage

Making basic GET, POST, PUT, PATCH or DELETE requests is very similar to what you’re used to with the old Http API. One major difference is that a JSON response is expected by default, so there’s no need to explicitly parse the JSON response anymore.

In new HttpClient, making GET, POST, PATCH, PUT and DELETE requests are very similar like the olf Http Api. Except a major change is that the response is in JSON format by default, so now we don’t need to manually parse our response into JSON. Let’s make a simple GET request:

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

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

getNewData() {
  this.http.get(this.url).subscribe(res => {
    this.posts = res;
  });
}

If you expect something other than JSON as the response, you can specify the expected response type using an object with the responseType key:

getData() {
  this.http.get(this.url, { responseType: "text" }).subscribe(res => {
    this.data = res;
  });
}

You can also define a custom interface for the shape of the response:

interface Post {
  title: string;
  body: string;
};

// ...

constructor(private http: HttpClient) {}

getData() {
  this.http.get<Post>(this.url).subscribe(res => {
    this.postTitle = res.title;
  });
}

Making POST, PUT and PATCH Requests

Making a POST, PUT or PATCH request is just as easy:

postNewData() {
  this.http.post(this.url, this.payload).subscribe();
}

Notice how we still have to subscribe in order for the request to be made. Without the subscribe call, the request is cold. You’ll obviously probably want to handle any response back or error:

postData() {
  this.http.post(this.url, this.payload).subscribe(
    res => {
      console.log(res);
    },
    (err: HttpErrorResponse) => {
      console.log(err.error);
      console.log(err.name);
      console.log(err.message);
      console.log(err.status);
    }
  );
}

A request error is of type HttpErrorResponse and contains, among others, an error name, error message and server status.


Options for passing-in headers or query parameters can also be added to a POST, PUT or PATCH request using the headers or params keys in the object passed-in as the 3rd argument:

updatePost() {
  this.http
    .put(this.url, this.payload, {
      params: new HttpParams().set('id', '121'),
      headers: new HttpHeaders().set('Authorization', 'some-token')
    })
    .subscribe(...);
}

Notice here the use of the HttpParams and HttpHeaders classes. You’ll need to import these from @angular/common/http as well.

So this was a basic introduction to Angular’s New HttpClient. If you want to learn more about Angular the check out our Learn Angular in 12 Days Series.

Recommended Resources to Learn Angular, Firebase and ionic 4

Muhammad Mubeen

Muhammad Mubeen

Mubeen is a full-stack web & mobile app developer who is very proficient in MEAN.js, Vue, Python, Ionic 4, Flutter, Firebase, ROR, and PHP. He has created multiple mobile and web applications. He is very passionate about sharing his knowledge.

Leave a Reply

Your email address will not be published. Required fields are marked *

Trending