Consuming a RESTful Web Service with Angular 4


REST stands for Representational State Transfer. It is a stateless software architecture that provides many underlying characteristics and protocols that govern the behaviour of clients and servers.

REST or HTTP based services are the primary requirements of single page applications to retrieve the data and gel into the web application. Angular offers its inbuilt HTTPClient service which wraps the major functions for requesting the data from server where REST service is hosted.

The Angular HttpClient API :-

Angular 4.3 introduced a new HttpClient service, which is a replacement for the Http service from Angular 2 and has it’s own package @angular/common/http. It works mostly the same as the old service, handling both single and concurrent data loading with RxJs Observables, and writing data to an API.

 

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

HttpClient service is included in the HttpClientModule and it can be used to initiate HTTP request.

 

Technologies Used :-

Find the technologies being used to build HTTPClient

1. Angular 4.3+

2. Angular CLI 1.5.4

3. TypeScript 2.4.2

4. Node.js 6.11.0

5. NPM 3.10.10

 

The Back-End API :-

The back-end for this app is a simple Express-based API that exposes the following endpoints:

GET/api/Authors

Returns an array of all existing Authors objects in JSON format.

POST/api/Authors

Creates a new Author object in the back-end data store. Accepts a JSON object in the request body. If successful, returns a 200 OK response, containing a JSON object representing the data as saved on the server, including the auto-numbered ID.

PUT/api/Authors/{Authors_id}

Updates an existing Author object. Accepts a JSON object in the request body. If successful, returns a 200 OK response, containing a JSON object representing the data as saved on the server.

DELETE /api/Authors/{Authors_id}

Deletes an existing Author object. Does not require a response body. If successful, returns a 200 OK response, containing a JSON object representing the Authors object as it existed before it was deleted.

Let’s see how to use the new HttpClient in Angular 4.3 project.

Setup an Angular 4.3 Project : –

The first step is to install Angular Cli command line interface.

If you have not installed Angular CLI on your system yet, you first need to execute the following command to install the latest version:

$ npm install -g @angular/cli

 

Now you can use the ng command to initiate a new Angular project:

$ ng new nghttp01

 

 

Screenshot from 2018-02-12 11-25-50

A new directory nghttp01 is created, the project template is downloaded and the dependencies are installed automatically.

Next open package.json in your code editor and check that all Angular dependencies contain a version number of >4.3.0.

Having updated the package.json file you need to execute the command in the project directory in order to make sure that the corresponding packages are updated.

$ npm install

Getting Started with HttpClient:-

To be able to use the HttpClient service within components you first need to include the HttpClientModule in the Angular application.

Import HttpClientmodule in the application’s root module in file app.module.ts:

Screenshot from 2018-02-12 11-56-37 (1)

 

Using HttpClient To Request Data :-

HttpClient will use the XMLHttpRequest browser API to execute HTTP request. In order to execute HTTP request of a specific type you can use the following methods which corresponds to HTTP verbs are

POST, GET, PUT, PATCH, DELETE, HEAD, JSONP

* To demonstrate the http methods, we would be querying a fake REST API

we create Service using angular cli. Write following angular cli command into terminal service makes the HTTP request and returns the Observable object.

$ ng g service app

 

It will create two files named app.service.ts and app.service.spec.ts.

Inject the HttpClient into an application class as shown in the following app.service.ts example.

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable'

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

@Injectable()
export class AppService {

  constructor(private http : HttpClient) { }
}

 

One of the most notable changes is that now the response object is a JSON by default, so there’s no need to parse it anymore for example :-

/* HttpClient */
this.http.get('https://api.github.com/users')
subscribe(data => console.log(data));

 

Rather Than

/* Http */
this.users = this.http.get('https://api.github.com/users')
.map(response => response.json())
.subscribe(data => console.log(data));

 

Example of an HTTPCLIENT GET:-

on app.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable'
import { Url } from './constant'

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

@Injectable()
export class AppService {

  constructor(private http: HttpClient) { }
  /* Uses http.get() to load data from a single API endpoint */
  getAuthors() {
    return this.http.get(Url.baseUrl + '/api/Authors');
  }
}

 

A component, such as app.component injects the app.service and calls the get service method.

import { Component } from '@angular/core';
import { AppService } from './app.service';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [AppService]
})
export class AppComponent {
  data: any = []
  author = {
    FirstName: '',
    ID: '',
    IDBook: '',
    LastName: ''
  }
  constructor(public appService: AppService) { }

  ngOnInit() {
    this.AuthorsPage();
  }
  /* method to call get-api from app.service */
  AuthorsPage() {
    try {
      this.appService.getAuthors()
        .subscribe(resp => {
          console.log(resp, "res");
          this.data = resp
        },
          error => {
            console.log(error, "error");
          })
    } catch (e) {
      console.log(e);
    }
  }
}

 

The subscribe() method takes three arguments which are event handlers. They are called onNext, onError, and onCompleted.

The onNext method will receive the HTTP response data. Observables support streams of data and can call this event handler multiple times. In the case of the HTTP request, however, the Observable will usually emit the whole data set in one call.

The onError event handler is called if the HTTP request returns an error code such as a 404.

The onCompleted event handler executes after the Observable has finished returning all its data. This is less useful in the case of the Http.get() call, because all the data we need is passed into the onNext handler.

The output which is displayed in the browser console should look like the following:

Screenshot from 2018-02-20 13-01-35

 

Example of an HTTPCLIENT Post :-

Next, let’s see how data can be send via HttpClient. For sending data we’ll be using the post method of the HttpClient object.

On app.service.ts :-

 /* Uses http.post() to submit data from a single API endpoint */
  submitAuthor(data) {
    return this.http.post(Url.baseUrl + '/api/Authors', data);

  }

 

On app.component.ts: –

  /* method to call post-api from app.service */
  submitAuth(formValues) {
    try {
      let author = {
        FirstName: formValues.FirstName,
        ID: formValues.ID,
        IDBook: formValues.IDBook,
        LastName: formValues.LastName
      }
      // console.log(author,"author")
      this.appService.submitAuthor(author)
        .subscribe(resp => {
          console.log(resp, "res");
          this.data = resp
        },
          error => {
            console.log(error, "error");
          })
    } catch (e) {
      console.log(e);
    }
  }

 

Here you can see that the data of the post request are passed to the post method as a second parameter in JSON format. We’re getting back a response which is confirming that the object has been created successfully.

Screenshot from 2018-02-12 15-56-16

 

Example of an HTTPCLIENT Put Method:-

This application update author with the HttpClient put method by passing the Author’s id and data in the request URL.

On app.service.ts

/* Uses http.put() to update data from a single API endpoint */
  updateAuthor(id,data) {
    return this.http.put('/api/Authors/' + id, data);
  }

 

Updating data from component:-

/* method to call put-api from app.service */
  updateFood(author,index) {
    try {
    this.appService.updateAuthor(author,index)
      .subscribe(data => {
       this.data = resp

      },
        error => {
          console.error("Error saving food!");
        }
      );
    }
    catch (e) {
      console.log(e);
    }
  }

 

Example of an HTTPCLIENT Delete method :-

This application deletes author with the HttpClient delete method by passing the Author’s id in the request URL.

On app.service.ts

 /* Uses http.delete() to delete data from a single API endpoint */
  deleteAuthor(id) {
    return this.http.delete(Url.baseUrl + "/api/Authors/" + id)
  }

 

deleting the data :-

/* method to call delete-api from app.service */
  deleteAuth(author, index) {
    try {
    this.appService.deleteAuthor(author)
      .subscribe(resp => {
        console.log(resp, "resp")

      },
        error => {
          console.log(error)
        }
      )
    }
    catch (e) {
      console.log(e);
    }
  }