【发布时间】: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);
}
}
【问题讨论】: