首页 > 解决方案 > 如果第一次失败,请在 Angular 中调用几次 API

问题描述

出于某种原因,我的外部 API 调用仅在 80% 的时间内工作,所以如果它失败了,我想至少尝试再调用 2-3 次,然后再给出错误。那可能吗?

下面是我的组件和服务文件中的一些代码。我抛出的错误在我的带有 getCars() 函数的组件文件中。我调用的 API 托管在 Heroku 上。

零件

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");
      }
    )
  };

服务

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);
  }
}

标签: angularrestheroku

解决方案


您可以retry为此使用运算符。

例如,以下示例将重试 3 次,然后最终返回错误。

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.


推荐阅读