代码之家  ›  专栏  ›  技术社区  ›  Atul

角6 http拦截器的正确行为

  •  1
  • Atul  · 技术社区  · 7 年前

    我写了一封信 Http Interceptor Angular 6 . 目标是在以下情况下重新加载主页: 302 status 他回来了。 我目前无法理解为什么 HttpInterceptor 现在的行为是这样的吗

    返回的API调用 302状态 在下面。 this._service.checkStatus() 调用返回的后端API 302 http status

    API代码:

    public checkStatus() : void  {
    
    
          this._service.checkStatus().subscribe(
    
            (data) => console.log('success In checkStatus '),
            (error)=>console.log('error In checkStatus')
          );
    
     }
    

    拦截器代码:

    export class MyInterceptor implements HttpInterceptor{
    
    
        constructor(){
    
        }
    
        intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    
            console.log('inside interceptor' );
            return next.handle(request).pipe(
    
            tap(
                    event =>{
                    },
                    error=>{
                        console.log(error);
    
                        if (error instanceof HttpErrorResponse) {
                            if (error.status === 302) {
                                window.location.reload();                      
                            }
                          }
                    }
                )
           );
    
        }
    
    }
    

    问题:

    302状态 返回时,该行 (error)=>console.log('error In checkStatus') checkStatus

    我的问题是,为什么API调用中的错误处理程序仍然被调用。 也就是说,在返回302之后,页面将重新加载 window.location.reload()

    但是错误处理程序 仍然会被调用。

    检查状态 应用程序编程接口?

    1 回复  |  直到 7 年前
        1
  •  2
  •   Michael Karén j3ff    7 年前

    用catchError试试看。

    return next.handle(request).pipe(   
    
         tap((event: HttpEvent<any>) => {
           console.log('tap', event);
         }),
    
         catchError(error => {
    
           console.log('catchError', error);
    
           if (error instanceof HttpErrorResponse) {
             if (error.status === 302) {
               window.location.reload();                      
             }
           }
    
           return throwError(error);     
         })
      )
    
    推荐文章