【问题标题】:Call an API in Angular a few times if it fails first time如果第一次失败,请在 Angular 中调用几次 API
【发布时间】:2019-04-19 22:49:37
【问题描述】:

由于某种原因,我的外部 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);
  }
}

【问题讨论】:

    标签: angular rest heroku


    【解决方案1】:

    您可以为此使用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)
          )
      }
    }
    

    这里有一个Sample StackBlitz 供您参考。如果您查看 StackBlitz,请打开开发工具并检查网络选项卡。它将发送大约 3 次请求,如果在所有情况下都失败,则会发出错误消息警报。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-31
      • 2017-05-20
      • 2023-01-13
      • 2012-07-31
      • 1970-01-01
      • 1970-01-01
      • 2018-10-19
      • 1970-01-01
      相关资源
      最近更新 更多