繁体   English   中英

如何处理 RxJs 超时完成 - Angular HttpClient

[英]How to handle RxJs timeout complete - Angular HttpClient

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

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

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",]

这有效

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 上实现了这个,代码在这里

您可以使用 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))
    );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM