0

For some reason, my external API call is only working like 80% of the time, so if it fails, I'd like to at least try calling it 2-3 more times before giving an error. Is that possible?

Below is some code from my component and service files. The error I'm throwing is in my component file with the getCars() function. The API I'm calling is hosted on Heroku.

Component

import { Component, OnInit } from '@angular/core';
import { CarsService, Car } from '../cars.service';

@Component({
  selector: 'app-car',
  templateUrl: './car.component.html',
  styleUrls: ['./car.component.css']
})
export class CarComponent implements OnInit {

  cars: Car[];

  constructor(
    public carService: CarsService
  ) { 
    this.getCars();
  }

  getCars(){
    this.carService.getCars().subscribe(
      data => {
        this.cars = data;
      },
      error => {
        alert("Could not retrieve a list of cars");
      }
    )
  };

Service

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from '../environments/environment';

export interface Car {
  make: string;
  model: string;
  year: string;
}

@Injectable({
  providedIn: 'root'
})
export class CarsService {

  baseUrl = environment.baseUrl;

  constructor(
    public http: HttpClient
  ) { }

  getCars() {
    let url = this.baseUrl + '/api/car'
    return this.http.get<Car[]>(url);
  }
}
James Mitchell
  • 2,387
  • 4
  • 29
  • 59

1 Answers1

2

You could use the retry operator for this.

The following eg, for instance, will retry for 3 times before finally returning an error.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from '../environments/environment';
import { retry } from 'rxjs/operators';

export interface Car {
  make: string;
  model: string;
  year: string;
}

@Injectable({
  providedIn: 'root'
})
export class CarsService {

  baseUrl = environment.baseUrl;

  constructor(
    public http: HttpClient
  ) { }

  getCars() {
    let url = this.baseUrl + '/api/car'
    return this.http.get<Car[]>(url)
      .pipe(
        retry(3)
      )
  }
}

Here's a Sample StackBlitz for your ref. If you have a look at the StackBlitz, open the Dev Tools and check the Network Tab. It will send the request about 3 times and if in all the cases, it fails, it will alert with the error message.

SiddAjmera
  • 38,129
  • 5
  • 72
  • 110