Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute a second http call only if first fails

Trying to pipe two Angular http calls where the second is executed only if the first one fails.

First call is:

 return this.http.get<AssetGroupHistoryResponseModel>('./assets/data.json');

If data.json is not present a 404 Not Found error is raised and it should call a proper API:

return this.http.get<AssetGroupHistoryResponseModel>(url);

Don't know how to obtain this behavior with rxjs.

like image 265
Alessandro Avatar asked Mar 12 '26 12:03

Alessandro


1 Answers

You can achieve that with the catchError operator from RXJS.

Here, give this a try:

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

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

  constructor(private http: HttpClient) {}

  ngOnInit() {
    this.getData()
      .subscribe(
        res => console.log(res)
      )
  }

  getData() {
    return this.http.get('http://jsonplaceholder.typicode.com/posts/1')
      .pipe(
        catchError(error => this.http.get('https://jsonplaceholder.typicode.com/users/1'))
      );
  }
}

PS: Notice that the first API call will result in an error as it uses http while the App will run on https. So you'll get user data logged to the console instead of the post data.


Here's a Working Sample StackBlitz for your ref.

like image 130
Patryk Panek Avatar answered Mar 15 '26 07:03

Patryk Panek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!