【问题标题】:How to handle RxJs timeout complete - Angular HttpClient如何处理 RxJs 超时完成 - Angular HttpClient
【发布时间】:2018-11-10 01:49:31
【问题描述】:

如何通过超时算子检测错误?我想在服务器没有响应时显示警报或类似的东西。

我的拦截器中有一个类似的代码:

this.http.post('http://localhost:3000/api/core', data)
        .pipe(
            timeout(30000),
            map((response: any) => { // Success...
              return response;
            }),
            catchError((error) => { // Error...
              // Timeout over also handled here
              // I want to return an error for timeout
              return throwError(error || 'Timeout Exception');
            }),
            finalize(() => {
              console.log('Request it is over');
            })
        );

["rxjs": "^6.0.0", "@angular/http": "^6.0.3",]

【问题讨论】:

  • 它会抛出一个TimeoutError,你可以使用instanceof来寻找它。

标签: angular rxjs timeout angular2-observables angular-httpclient


【解决方案1】:

这行得通

import { throwError, TimeoutError } from 'rxjs';

catchError((error) => { // Error...
   // Handle 'timeout over' error
   if (error instanceof TimeoutError) {
      return throwError('Timeout Exception');
   }

   // Return other errors
   return throwError(error);
})

我在具有其他功能的 intecerptor 上实现了这个,代码 here

【讨论】:

  • 找不到页面。你能再上传一次吗?
  • 嘿。这对我有用,但我仍然收到错误 ERROR Error: Uncaught (in promise): TimeoutError: Timeout has occurred
  • 如果你不想返回错误(你应该)而不是“throwError”返回“of”。您可以在地图中处理,或点击运算符
  • 我返回的是错误而不是被捕获。现在它正在工作。谢谢
【解决方案2】:

你可以使用 timeoutWith 操作符来实现。

return this.http.post('http://localhost:3000/api/core', data).pipe(
      timeoutWith(3000, observableThrowError(new Error('Http Timeout exceeds'))),
      map((response: any) => { // Success...
              return response;
      }),
      catchError((error: HttpErrorResponse) => this.handleError(error))
    );

【讨论】:

  • observableThrowError?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-05
相关资源
最近更新 更多