Best way for multiple HTTP Request in Angular

Prag Dopravy

I am trying to send 2 HTTP requests one by one; if the first one is succeeds, send the second one, if not display the corresponding error message regarding to the first request.

I am planning to use something like that, but not sure if it is the best option for this scenario:

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: 'app/app.component.html'
})
export class AppComponent {
  loadedCharacter: {};
  constructor(private http: HttpClient) {}

  ngOnInit() {
    this.http.get('/api/people/1').subscribe(character => {
      this.http.get(character.homeworld).subscribe(homeworld => {
        character.homeworld = homeworld;
        this.loadedCharacter = character;
      });
    });
  }
}

I have different requests e.g. PUT and CREATE also using this approach. I know there are other ways e.g. forkjoin, mergemap, but if this one solves my problem seems to be more readable. Any idea?

Yevhenii Dovhaniuk

First of all, your code works and that's great - you can leave it as is and everything will be fine.

On the other hand, there is a way for multiple improvements that will help you and your colleagues in future:

  1. try to move http-related logic to the service instead of calling http in the components - this will help you to split the code into view-related logic and the business/fetching/transformation-related one.
  2. try to avoid nested subscribes - not only you ignore the mighty power of Observables but also tie the code to a certain flow without an ability to reuse these lines somewhere in the application. Returning the Observable might help you with "sharing" the results of the request or transforming it in some way.
  3. flatMap/mergeMap, concatMap and switchMap work in a different way, providing you an ability to control the behaviour the way you want. Though, for http.get() they work almost similar, it's a good idea to start learning those combining operators as soon as possible.
  4. think about how you'll handle the errors in this case - what will happen if your first call will result an error? Observables have a powerful mechanism of dealing with them, while .subscribe allows you to handle an error only in one way.

An example using the switchMap:

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: 'app/app.component.html'
})
export class AppComponent {
  loadedCharacter: {};
  constructor(private http: HttpClient) {}

  ngOnInit() {
    const character$ = this.http.get('/api/people/1').pipe(
      tap(character => this.characterWithoutHomeworld = character), // setting some "in-between" variable
      switchMap(character => {
        return this.http.get(character.homeworld).pipe(
            map(homeworld => {
                    return {
                        ...character,
                        homeworld: homeworld
                    }
                }
            )
        )
      }),
      catchError(errorForFirstOrSecondCall => {
        console.error('An error occurred: ', errorForFirstOrSecondCall);
        // if you want to handle this error and return some empty data use:
        // return of({});
        
        // otherwise: 
        throw new Error('Error: ' + errorForFirstOrSecondCall.message);
      })
);

    // you can either store this variable as `this.character$` or immediately subscribe to it like:
    character$.subscribe(loadedCharacter => {
        this.loadedCharacter = loadedCharacter;
    }, errorForFirstOrSecondCall => {
       console.error('An error occurred: ', errorForFirstOrSecondCall);
    })
  }
}


Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Best Way for handling HTTP 503 in post request

Best way to specify the local endpoint for HTTP request?

Flutter - Best way to request Multiple APIs simultaneously

Best way to validate multiple fields in a request

Best way to work with multiple http calls in NodeJS

Java best way to send multiple HTTP requests

Angular multiple input search request with http request

Best way to set default header for all request in flutter http request

What is the best way working multiple projects with angular?

The best way to set the timeout on built-in HTTP request

Whats the best way to handle optional field in PUT http request at backend

What is the best way to make an HTTP request from a Java program?

Best way to mitigate null HTTP request in apache2

Angular 6 multiple HTTP request RxJs

How to send Multiple Http request sequentially in Angular

Angular 2 - Multiple HTTP request in the same time

Angular 6 best way to sequence functions that are not http oriented

What is the best way to use observables for http requests in angular?

What is the best way to implement sequencial http requests with optimistic concurrency in angular?

The best way to share WebSocket data between multiple components in Angular 2?

what is best way to reuse components in multiple projects in angular?

Angular - What's the best way to include html in multiple components?

Is there standard way of making multiple API calls combined into one HTTP request?

Angular 5 HTTP Get request Parameters - Send multiple objects

Http request made multiple times in Angular2 service

Angular 4 http get with multiple params to Spring Request Mapping

Resolve multiple promises and send angular 2 http request

Angular 2 - Multiple HTTP get request and cache response

Single Angular Controller w/ multiple $HTTP Get request