How to intercept request to component html templates in Angular 4.3.5

三世轮回 提交于 2019-12-25 00:56:16

问题


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?


回答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



来源:https://stackoverflow.com/questions/46344799/how-to-intercept-request-to-component-html-templates-in-angular-4-3-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!