Handle multiple observables in Angular

share link

by Abdul Rawoof A R dot icon Updated: Jan 22, 2024

technology logo
technology logo

Guide Kit Guide Kit  

Observables offer help passing messages among elements of your application. Developers use them in Angular as a technique for event handling. They also use them for asynchronous programming and handling many values. 


 Angular uses observables as an interface to manage many familiar asynchronous operations. For example, the HTTP module utilizes observables to handle AJAX requests and responses. The Router and Forms modules use observables to listen for user-input events. They also use observables to respond to these events. We can use the concat operator to combine many Observables. It creates a new Observable that emits values from each Observable in sequence. It works through the means of subscribing to them for my part and merging the outcomes in Observable output. An Observable will emit activities. A described callback executes for every event. If you need to address an unmarried event, use Promise. If you need to circulate a couple of activities from the identical API, use Observables. 


 Types of Observables in Angular:  


  • Observable.  
  • Flowable.  
  • Single.  
  • Completable. 


Here is an example of how to handle multiple observables in Angular: 

Fig: Preview of the output that you will get on running this code from your IDE.

Code

{
  "count": 964,
  "next": "https://pokeapi.co/api/v2/pokemon/?offset=3&limit=3",
  "previous": null,
  "results": [
    {
      "name": "bulbasaur",
      "url": "https://pokeapi.co/api/v2/pokemon/1/"
    },
    {
      "name": "ivysaur",
      "url": "https://pokeapi.co/api/v2/pokemon/2/"
    },
    {
      "name": "venusaur",
      "url": "https://pokeapi.co/api/v2/pokemon/3/"
    }
  ]
}

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

import { of, forkJoin } from 'rxjs';
import { map, catchError, tap } from 'rxjs/operators';

export const BASE_URL = 'https://pokeapi.co/api/v2';

@Injectable()
export class PokemonApiService {

  constructor(private httpClient: HttpClient) { }

  public getListOfPokemon(limit: string, offset ?: string) {
    const params = new HttpParams()
      .set('offset', offset ? offset : '0')
      .set('limit', limit);
    return this.httpClient
      .get<any>(`${BASE_URL}/pokemon`, { observe: 'response', params: params })
      .pipe(
        map(res => res.body.results),
        catchError(error => of(error.url))
      );
  }

  public getPokemonDetails(urlList: Array<any>) {
    urlList = urlList.map(url => this.httpClient.get<any>(url));
    return forkJoin(urlList);
  }
}

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map, catchError, tap } from 'rxjs/operators';

import { PokemonApiService } from './pokemon-api.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  pokemons = [];
  limit = '50';

  constructor(private _pokemonApiService: PokemonApiService) {}

  ngOnInit(){
    this.getPokemonList();
  }

  private getPokemonList() {
    this._pokemonApiService.getListOfPokemon(this.limit).subscribe(
      response => { this.getPokemonDetails(response.map(response => response.url)); },
      error => { console.error(error); }
    );
  }

  private getPokemonDetails(urlList: Array<string>) {
    this._pokemonApiService.getPokemonDetails(urlList).subscribe(
      response => { this.pokemons = response; },
      error => { console.error(error); }
    );
  }

}

<table>
  <tr>
    <th>ID</th>
    <th>Name</th>
    <th>Sprite</th>
  </tr>
  <tr *ngFor="let pokemon of pokemons">
    <td>{{ pokemon.id }}</td>
    <td>{{ pokemon.name | titlecase }}</td>
    <td><img [src]="pokemon.sprites.front_default"/></td>
  </tr>
</table>

Instructions

Follow the steps carefully to get the output easily.

  1. Install Visual Studio Code on your computer.
  2. Open terminal, install Angular using this command-'npm install -g @angular/cli@latest'.
  3. Create new folder using the command-'ng new folder_name'.
  4. Then open the folder from File->Open Folder.
  5. Create a new ts file(eg: search-user.pipe.ts).
  6. Now click this link , to know where the code needs to be placed in their respective files.
  7. Save the files and open the terminal, use this command-'ng serve' to generate the output in localhost.


I hope you found this helpful.


I found this code snippet by searching for 'handle multiple observables in angular' in kandi. You can try any such use case!

Environment Tested

I tested this solution in the following versions. Be mindful of changes when working with other versions.

  1. The solution is created and tested in Visual Studio Code 1.74.1.
  2. The solution is test in Angular CLI - 15.2.2.


Using this solution, we are able to handle multiple observables in Angular with simple steps. This process also facilities an easy way to use, hassle-free method to create a hands-on working version of code which would help us to handle multiple observables in Angular.

 FAQ 

 1.How can I manage many observables in Angular?  

Use the fork Join operator to handle many observables. Ensure they are all completed before proceeding. 


 2.Can I handle errors when dealing with many observables?  

Yes, fork Join allows you to handle errors. If any observable experiences an error, the entire operation  

is unsuccessful.  


3. What happens if one observable fails in a pack of many observables? 

 If any visible in the fork Join set breaks, it will trigger the error callback. This provides an opportunity to handle the error.  


4. Is there an alternative to Fork Join for handling many observables?  

Another option is combine Latest. It emits whenever any observable emits a value. Keep in mind that it might not wait for all observables to complete.  


5. Can I handle many HTTP requests using fork Join?  

Yes, in Angular, we use fork Join to make parallel HTTP requests. It allows you to fetch data from many endpoints. 

Support

  1. For any support on kandi solution kits, please use the chat
  2. For further learning resources, visit the Open Weaver Community learning page.