我在使用 Angular 拦截器时遇到了问题。我有一个
fetch
的 HTTP GET 请求,我想要在请求失败时通过拦截器捕获错误。但是当我发送 GET 请求时,我的拦截器无法工作。拦截器无法看到这个请求。当我编辑 GET 请求并使用 HttpClient(this.http.get...)时,一切都正常,能够工作。我该如何同时使用 fetch 和拦截器?@Injectable()
export class TestInterceptor implements HttpInterceptor {
constructor() {
console.log('constructor of interceptor');
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log('interceptor work');
return next.handle(req);
}
}
@NgModule({
declarations: [
TestComponent
],
imports: [
SharedModule,
HttpClientModule
],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: TestInterceptor,
multi: true
},
]
})
export class TestModule {}
sendRequest(url: string, method = 'GET', body = null): Promise<any> {
let response: Response;
return fetch(url, {
method,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: body ? JSON.stringify(body) : null
});
}