2017-09-23 127 views
0

我爲我的角度應用程序編寫了一個錯誤攔截器,以便在檢測到401時將用戶路由到登錄頁面。Angular:ErrorInterceptor not beeing called

奇怪的是,從來沒有調用錯誤塊。只有入口和成功控制檯日誌條目在我的控制檯中。

任何想法可能是錯誤的?

import { Injectable } from '@angular/core'; 
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from '@angular/common/http'; 
import { Observable } from 'rxjs/Observable'; 
import 'rxjs/add/operator/do'; 
import {Router} from '@angular/router'; 
import { HTTP_INTERCEPTORS } from '@angular/common/http'; 

@Injectable() 
export class ErrorInterceptor implements HttpInterceptor { 

    constructor(private router: Router) { 
    } 

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { 

     console.log('interceptor called'); 

     return next.handle(req).do(event => { 
      console.log('interceptor in success', event); 
     }, err => { 

      console.log('interceptor in error', err); 

      if (err instanceof HttpErrorResponse && err.status === 401) { 

       this.router.navigate(['/login']); 
      } 
     }); 
    } 
} 


export const errorInterceptorProvider = { 
    provide: HTTP_INTERCEPTORS, 
    useClass: ErrorInterceptor, 
    multi: true, 
}; 

攔截器集成在我的應用程序模塊:

providers: [ 
    ... 
    errorInterceptorProvider 
    ], 
+0

請問您可以添加一個完整的示例嗎?這不會編譯 – netshark1000

回答

0

它應該看到https://plnkr.co/edit/mQnrJQarp4wRaohKNzre?p=preview

另一種選擇是使用catch操作:

... 
import 'rxjs/add/operator/do'; 
import 'rxjs/add/operator/catch'; 
import 'rxjs/add/observable/empty'; 
import 'rxjs/add/observable/throw'; 
import 'rxjs/add/operator/finally'; 

@Injectable() 
export class ErrorInterceptor implements HttpInterceptor { 

    constructor(private router: Router) {} 

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { 
    console.log('interceptor called'); 

    return next.handle(req) 
     .do(event => { 
     console.log('interceptor in success', event) 
     }) 
     .catch(err => { 
     console.log('interceptor in error', err); 
     if (err instanceof HttpErrorResponse && err.status === 401) { 
      this.router.navigate(['/login']); 
     } 
     return Observable.throw(err); 
     // or return Observable.empty(); 
     }) 
     .finally(() => { 
     console.log('finally'); 
     }); 
    } 
} 

Plunker Example

+0

mhh ...再次錯誤不會被調用。可能是什麼原因? – netshark1000

+0

你可以創建一個例子來重現它嗎? – yurzui

+0

解決了...另一個攔截器有干擾 – netshark1000