I have written http interceptor in angular but I cannot see js request coming in the interceptor handler. I wanted to intercept the some js request and do some handling around it.
I am looking to intercept request like
Request URL: http://localhost:5000/chunk1.js
@Injectable()
export class SimpleInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req); // js request is not coming here.
}
}
Let me know if there is something else to intercept js request?
Note: I am working on angular lazy-loading and want to intercept the chunk loading request and change the host of request.
CodePudding user response:
Interceptors need to be registered as providers in app module.
@NgModule({
imports: [ BrowserModule, FormsModule, HttpClientModule ],
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: MyHttpInterceptor, multi: true }
],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
And as @Matthieu wrote, just if you will use httpclient to triger calls will work.
CodePudding user response:
The only way to intercept all requests is in the ServiceWorker with the fetch listener.
self.addEventListener('fetch', function(event) {
const url = event.request.url;
// do what you need
})