Angular 13 Observable Asynchronous HTTP Request Tutorial

Comprehensive Angular RxJS Observable tutorial, this guide will help you discover how to make an asynchronous HTTP request in Angular using the RxJS observable.

RxJS is an impeccable framework for handling asynchronous and event-based programs; this library works on the robust observable pattern, it is also known as reactive programming. RxJS introduced to empower JavaScript.

It is an ultimate elixir for programmers; they get top-notch performance, greater flexibility, profound debugging support, not just that but also backward compatibility.

RxJS is a collective combination of the Observer pattern, Iterator pattern on top of that functional programming with collections that help handle the events’ sequences.

Observables in Angular

In this angular RxJS Observable example, we use the observable interface to make the asynchronous HTTP GET request to fetch the data from the remote server.

Additionally, Observable in Angular are useful for creating custom events, and custom events help in transferring data from one component to another component.

Likewise, AJAX requests are also well synced with Observables in conjunction with HTTP modules and smoothly handle the response. Nonetheless, this detailed guide will share with you how to use observable to handle httpclient requests in angular project.

Angular 13 Observable Asynchronous HTTP Request Example

Here are the steps that you have to follow gradually to understand the concept of angular observable:

  • Step 1: Install Angular Project
  • Step 2: Register HttpClientModule
  • Step 3: Create User Interface
  • Step 4: Generate & Configure Angular Service
  • Step 5: Handle HTTP Observable Response
  • Step 6: Display Data
  • Step 7: Test Angular App

Install Angular Project

Before you start with this guide, ensure you have the latest angular CLI installed on your development machine:

npm install -g @angular/cli

Thereafter, open terminal on top of that run the recommended command to install a brand new angualr app:

ng new angular-observable-http-demo

Next, move to project folder’s root:

cd angular-observable-http-demo

Disable Strict Angular TypeStrict Errors

The latest version of Angular comes with strict mode, you have to manually disable the strict mode you can set “strict”: false, "noImplicitReturns": false and "strictTemplates": false inside the compilerOptions and angularCompilerOptions in tsconfig.json file.

Register HttpClientModule in App Module

Open app.module.ts file, then import HttpClientModule from ‘@angular/common/http’ package including register the HttpClientModule in imports array.

Now, the HttpClient module is available throughout the angular components, including XSRF service support.

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

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

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


@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule { }

Create User Interface

For enabling the type checking in angular, we need to create an interface class, hence execute the offered command:

ng generate interface user

Open and update user.ts interface file:

export interface User {
    id: number,
    name: string,
    username: string,
    email: string    
}

Generate & Configure Angular Service

First, genrate the service component with reccomended command:

ng generate service user

Open user.service.ts file similarly update the following code:

import { Injectable } from '@angular/core';

import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';

import { User } from './user';

@Injectable({
  providedIn: 'root'
})

export class UserService {

  private API: string = 'https://jsonplaceholder.typicode.com/users';

  constructor(private httpClient: HttpClient) { }
  
  getUsers(): Observable<User[]> {
    return this.httpClient.get<User[]>(`${this.API}`)
  }

  // Error handling
  handleError(error: HttpErrorResponse) {
    let errorMessage = '';
    if (error.error instanceof ErrorEvent) {
      errorMessage = error.error.message;
    } else {
      errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
    }
    console.log(errorMessage);
    return throwError(errorMessage);
  }

}

To use observable in angular, make sure to import it, moreover to handle the error gracefully also, import the throwError from rxjs package.

You can define your API in API variable, similarly import and inject HttpClient in the constructor method.

The HttpClient API provides all the options that are essential for making HTTP requests.

Handle HTTP Observable Response in Component

Let us check out how to incorporate angular service in TypeScript and HTML components.

Add the example code in app.component.ts file:

import { Component } from '@angular/core';

import { UserService } from './user.service';
import { User } from './user';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})

export class AppComponent {
  
  USERS = new Array<User>();
    
  constructor(private userService: UserService) {}
    
  ngOnInit(): void {
    this.userService.getUsers().subscribe(res => {
      this.USERS = res;
    });
  }

}

Display Data

Next, you can easily display the data from the response we received from observable HTTP.

Hecne, add the example code in app.component.html file:

<table class="table">
  <thead>
    <tr class="table-primary">
      <th>#User Id</th>
      <th>Name</th>
      <th>User Name</th>
      <th>Email</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let data of USERS">
      <th scope="row">{{data.id}}</th>
      <td>{{data.name}}</td>
      <td>{{data.username}}</td>
      <td>{{data.email}}</td>
    </tr>
  </tbody>
</table>

Test Angular App

All the work has been done, now start the application hence open the terminal use the provided command:

The above command manifest the following url, that you can use to test the app:

http://localhost:4200

Angular 12 Observable Asynchronous HTTP Request Tutorial

Conclusion

The Angular HTTP Observable example tutorial is completed; in this extensive example, you understood what observable is, how to use RxJS observables to make the asynchronous HTTP request to get the data from the server in the angular app.

We have just seen the tip of the iceberg; nevertheless, you can try more with Observables in Angular.