问题描述: 在使用Angular的HttpInterceptor时,发现当发生错误时,HttpInterceptor不会被调用。
解决方法:
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
HttpClientModule
],
...
})
export class AppModule { }
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { MyHttpInterceptor } from './my-http-interceptor';
@NgModule({
...
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: MyHttpInterceptor,
multi: true
}
],
...
})
export class AppModule { }
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
export class MyHttpInterceptor implements HttpInterceptor {
intercept(request: HttpRequest, next: HttpHandler): Observable> {
return next.handle(request).pipe(
catchError((error) => {
// 处理错误逻辑
console.error('An error occurred:', error);
return throwError(error);
})
);
}
}
通过以上步骤,应该能够解决Angular的HttpInterceptor在错误发生时不被调用的问题。如果问题仍然存在,可以检查浏览器的开发者工具中的网络请求,以查看是否收到了从服务器返回的错误响应。