【问题标题】:Angular how to know if a request has timeout more than three times?Angular如何知道请求是否超时超过三倍?
【发布时间】:2019-02-08 03:46:14
【问题描述】:

我有一个 Angular 4 应用,它在浏览整个应用时有很多持续的 http 请求

我也想在http超时发生3次或更多的时候做点什么。

http 请求中可能会发生其他错误,但我只想关注超时错误。

我的 http_interceptor 中有以下代码。

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const re = '/u/auth/login';
    const defaultTimeout = 10000;

    if (req.url.search(re) || req.url.search('api.giphy.com/v1') === -1) {
        const headers = new HttpHeaders({
            Authorization: `Bearer ${localStorage.getItem('token')}`,
            // 'Content-Type': 'application/json'
        })
        const dupReq = req.clone({headers});
        const timeOut = Number(req.headers.get('timeout')) || this.defaultTimeout
        return next.handle(dupReq).pipe(
          timeout(timeOut),
          catchError(e => {
            return of(null)
          })
        )
    } else {
        return next.handle(req)
    }
  }

如何处理超时错误以及如何知道它们发生了 3 次或更多。我会对每个错误进行增量吗?并且只使用条件来执行该功能?

作为一个额外的问题,我如何才能成功回调拦截器的句柄?

如果有人可以提供帮助,我们将不胜感激。 提前致谢。

【问题讨论】:

    标签: angular http timeout httpclient angular-http-interceptors


    【解决方案1】:

    在订阅方法之上的链式 retryWhen 方法。

    import 'rxjs/add/operator/retryWhen';
    import 'rxjs/add/operator/delay';
    import 'rxjs/add/operator/scan';
    
    .retryWhen((err)=> {
            return err.scan((attempt) => {
                if(attempt>5){
                    throw(err);
                }else{
                    attempt++;
                    console.log("attempt number "+attempt);
                    return attempt;
                }
            },0
            ).delay(1000)
        })
    

    【讨论】:

    • 我试过这样return next.handle(dupReq).pipe( timeout(timeOut), catchError(e =&gt; { return of(e) }), retryWhen(err =&gt; { return err.scan(attempt =&gt; { if (attempt &gt; 5) { throw(err); } else { attempt++; console.log("attempt number "+attempt); return attempt; } }, 0) }).delay(1000) ) 但我得到一个错误类型'void'的'this'上下文不可分配给方法的
    猜你喜欢
    • 2016-07-29
    • 1970-01-01
    • 1970-01-01
    • 2011-02-26
    • 1970-01-01
    • 2020-06-23
    • 2018-04-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多