Angular : How to make REST API Calls ?

In this tutorial we will learn about Angular REST API Calls.

Note : Module to be used for REST API Call

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

In src/app/app.module.ts file import HttpClientModule and add it to the imports array:

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

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
    // [...]
    HttpClientModule,
  ],
  // [...]
})
export class AppModule { }

SERVICE class : to write all the CRUD API requests

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 ApiService {
 
    constructor(private http:HttpClient) {}
}

GET API Request in Angular

Now adding a get method in ApiService for the GET API request.

    // Uses http.get() to load data from a single API endpoint
    getEmployees() {
        return this.http.get('/api/employees');
    }

Our ApiService makes the HTTP request and returns an Observable object. To actually get the data from the service, we need to update our component to subscribe to the Observable. Lets check below.

app.component.ts

ngOnInit() {
    this.getEmployees();
  }
 
  getEmployees() {
   this._apiService.getEmployees().subscribe(
      data => { this.employees = employees },
      err => console.error(err),
      () => console.log('done loading employees')
    );
  }
}

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.

Other HTTP Request : PUT, Delete, POST http requests

Now we will write other HTTP methods like PUT, POST and DELETE in our ApiService layer.

@Injectable()
export class ApiService {
 
    constructor(private http:HttpClient) {}
 
    ...
 
    createEmployee(employee) {
        let body = JSON.stringify(employee);
        return this.http.post('/api/employee/', body, httpOptions);
    }

    updateEmployee(employee) {
        let body = JSON.stringify(employee);
        return this.http.put('/api/employee/' + employee.id, body, 
                             httpOptions);
    }

    deleteEmployee(employee) {
        return this.http.delete('/api/employee/' + employee.id);
    }
 
}

Retrying – retry GET API call on fail

Sometimes the error is transient and will go away automatically if you try again. For example, network interruptions are common in mobile scenarios, and trying again may produce a successful result.

The RxJS library offers several retry operators that are worth exploring. The simplest is called retry() and it automatically re-subscribes to a failed Observable a specified number of times. Re-subscribing to the result of an HttpClient method call has the effect of reissuing the HTTP request.

Pipe it onto the HttpClient method result just before the error handler.

getConfig() {
  return this.http.get<Config>(this.configUrl)
    .pipe(
      retry(3), // retry a failed request up to 3 times
      catchError(this.handleError) // then handle the error
    );
}

Executing multiple concurrent HTTP requests – using forkJoin ()

Many times, we need to load data from more than one source, and we need to delay the post-loading logic until all the data has loaded. ReactiveX Observables provide a method called forkJoin() to wrap multiple Observables. Its subscribe() method sets the handlers on the entire set of Observables.

...

@Injectable()
export class ApiDemoService {
 
    constructor(private http:HttpClient) {}
 
    // Uses Observable.forkJoin() to run multiple concurrent http.get() 
    // requests.
    // The entire operation will result in an error state if any single 
    // request fails.
    
    getEmployeesAndRole() {
        return Observable.forkJoin(
        this.http.get('/api/employees'),
        this.http.get('/api/roles')
        );
    }
}

Now subscribe to the service

export class AppComponent {
 
+  public employees;
+  public roles;

 
+  getEmployeesAndRole() {
+    this._apiDemoService.getEmployeesAndRole().subscribe(
+      data => {
+        this.employees= data[0]
+        this.roles= data[1]
+      }
+      // No error or completion callbacks here. They are optional, but
+      // you will get console errors if the Observable is in an error state.
+    );
+  }
 
}

Summary

In this tutorial we learnt about Angular REST API Calls. We saw examples of all the CRUD api calls in angular, we saw how to retry an api call on fail and we also learnt how to make multiple concurrent HTTP requests using forkJoin Observable method.
I hope you liked it !


Leave a Comment