我爲我的角度應用程序編寫了一個錯誤攔截器,以便在檢測到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
],
請問您可以添加一個完整的示例嗎?這不會編譯 – netshark1000