在 Angular 中 httpClient 超时时调用函数

call a function in case of httpClient timeout in Angular

我有一个函数在服务器上发送几个请求,每个请求都有超时:

this.httpClient.get(url, { headers: headers })
        .timeout(30000)
        .subscribe(
            (response) => {
                ...
            },
            error => {
                ...
            }
                ...
            );

如果超时(30s),所有请求都会被取消,这是可以理解的。 我的问题是,在超时的情况下,取消的请求不会被视为错误,因此它不会转到请求的错误部分。 在这种情况下是否可以调用函数?

如果你使用的是Angular6,超时处理的方法是pipe/timeout,请看这个例子:

this.http.get('https://httpstat.us/200?sleep=5000')
  .pipe(timeout(1000))
  .subscribe(response => {
    console.log('forceTimeout', response);
  }, (error) => {
    console.log('Error', error);
    this.error = error.constructor.name;
  })

此片段来自我为演示 HTTP 拦截器而编写的示例:https://stackblitz.com/edit/angular-my-http-interceptor?file=src%2Fapp%2Fapp.component.ts