简体   繁体   中英

Can we intercept js request in Angular?

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.

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.

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 
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM