How to intercept request to component html templates in Angular 4.3.5
Asked Answered
P

1

1

I need to intercept request to the html component templates. Angular version is 4.3.5.

I tried to achieve it with implementing interceptors as described in angular httpClient manual (https://angular.io/guide/http) like that

interceptor.service.js

import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  constructor(private auth: AuthService) {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // Get the auth header from the service.
    const authHeader = this.auth.getAuthorizationHeader();
    // Clone the request to add the new header.
    const authReq = req.clone({headers: req.headers.set('Authorization', authHeader)});
    // Pass on the cloned request instead of the original request.
    return next.handle(authReq);
  }
}

app.module.js

import {NgModule} from '@angular/core';
import {HTTP_INTERCEPTORS} from '@angular/common/http';

@NgModule({
  providers: [{
    provide: HTTP_INTERCEPTORS,
    useClass: NoopInterceptor,
    multi: true,
  }],
})
export class AppModule {}

but it intercepts http requests from services and components which i wrote by myself but doesn't intercept requests to html templates which are made by angular.

Is there any other way to do it?

Puleo answered 21/9, 2017 at 13:8 Comment(9)
What are you trying to achieve?Dicky
#42413526Dicky
@Dicky i want to add custom parameter in the end of request url to prevent caching issuesPuleo
How do you build your application?Dicky
@Dicky platformBrowserDynamic().bootstrapModule(Ng2App) where Ng2App is main application modulePuleo
angular-cli, webpack, systemjs?Dicky
i am using systemjsPuleo
Are you using aot?Dicky
@Dicky no, i don't use aot. I will try to use ResourceLoader, thanks a lot!Puleo
D
1

If you can have access to @angular/compiler then try to override ResourceLoader:

main.ts

platformBrowserDynamic([{
    provide: COMPILER_OPTIONS,
    useValue: { providers: [{ 
                  provide: ResourceLoader, 
                  useClass: CustomResourceLoader, 
                  deps: [] 
              }]
    },
    multi: true
}]).bootstrapModule(AppModule);

Plunker Example

Dicky answered 21/9, 2017 at 13:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.