在Angular 7中,可以使用retryWhen
操作符来在特定的响应状态码上重试HTTP请求。下面是一个示例:
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { retryWhen, mergeMap, delay, take, catchError } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(private http: HttpClient) {}
public get(url: string): Observable {
return this.http.get(url).pipe(
retryWhen(errors => {
return errors.pipe(
mergeMap((error: HttpErrorResponse) => {
if (error.status === 500) {
// 重试5次,每次间隔1秒
return throwError(error).pipe(delay(1000), take(5));
} else {
return throwError(error);
}
}),
catchError((error: HttpErrorResponse) => {
// 处理其他错误
return throwError(error);
})
);
})
);
}
}
在上面的代码中,get
方法发送一个HTTP GET请求,并使用retryWhen
操作符来处理错误。在retryWhen
中,我们可以使用mergeMap
操作符来检查响应的状态码。如果状态码为500,则使用throwError
创建一个新的Observable,并使用delay
和take
操作符来设定重试次数和间隔时间。如果错误不是500,则直接抛出错误。
在使用这个ApiService
时,可以像下面这样进行调用:
import { Component } from '@angular/core';
import { ApiService } from './api.service';
@Component({
selector: 'app-root',
template: `
Data: {{ data }}
`
})
export class AppComponent {
data: any;
constructor(private apiService: ApiService) {}
getData() {
const url = 'https://api.example.com/data';
this.apiService.get(url).subscribe(
response => {
this.data = response;
},
error => {
console.error(error);
}
);
}
}
在上面的代码中,当点击按钮时,会调用getData
方法来获取数据。使用apiService
发送HTTP请求,并订阅返回的响应。如果请求失败或返回状态码为500,它将进行重试。