由于某种原因,我的外部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);
}
}
答案 0 :(得分:2)
您可以为此使用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次,如果在所有情况下均失败,它将发出错误消息警报。