angular - 如果第一次失败,请在 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);
}
}
解决方案
您可以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.
推荐阅读
- allegrograph - 在 Arch Linux 上安装 AllegroGraph 时出错
- javascript - 试图让函数完成,以便它可以在 node.js 中返回带有承诺的数据
- vue.js - 将组件名称传递给 Vue 应用程序中的标题字段
- docker - 在特定持续时间后自动停止 Docker 容器
- openldap - 什么是 idassert 绑定?为什么我们需要在 openldap 代理中使用 idassert-bind?
- active-directory - Ansible AWX 中的 LDAP 和 memberOf 属性
- android - Android 9 中的蓝牙权限
- kubernetes - helm init 已在版本 3 中删除
- .net - 如何避免 .NET SSLStream 中的内存泄漏
- regex - linux bash 正则表达式只找到第一次出现