Angular 的 HTTPClient.get 方法包含一个可选的配置参数,其中可以指定超时时间。如下所示:
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { catchError, timeout } from 'rxjs/operators';
import { throwError } from 'rxjs';
@Injectable()
export class MyService {
constructor(private http: HttpClient) {}
getData() {
return this.http.get('https://example.com/data', { timeout: 5000 })
.pipe(
timeout(5000),
catchError(this.handleError)
);
}
private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
console.error('An error occurred:', error.error.message);
} else {
console.error(`Backend returned code ${error.status}, ` +
`body was: ${error.error}`);
}
return throwError(
'Something bad happened; please try again later.');
};
}
在上面的代码中,我们在 HTTP GET 调用中设置了超时时间为 5 秒钟(5000 毫秒)。如果请求超过此时间,就会抛出一个错误。 timeout 操作符用于确保 Observable 在指定的时间内发出数据,如果时间超时,则 Observable 会发出错误。我们还使用 catchError 操作符来处理 HTTP 错误。