如何在 Angular 4.3.5 中拦截对组件 html 模板的请求
How to intercept request to component html templates in Angular 4.3.5
我需要拦截对 html 组件模板的请求。 Angular 版本为 4.3.5
.
我试图通过实现拦截器来实现它,如 angular httpClient 手册 (https://angular.io/guide/http) 中所述
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 {}
但它会拦截来自我自己编写的服务和组件的 http 请求,但不会拦截由 angular.
对 html 模板发出的请求
还有其他方法吗?
如果您可以访问 @angular/compiler
然后尝试覆盖 ResourceLoader
:
main.ts
platformBrowserDynamic([{
provide: COMPILER_OPTIONS,
useValue: { providers: [{
provide: ResourceLoader,
useClass: CustomResourceLoader,
deps: []
}]
},
multi: true
}]).bootstrapModule(AppModule);
我需要拦截对 html 组件模板的请求。 Angular 版本为 4.3.5
.
我试图通过实现拦截器来实现它,如 angular httpClient 手册 (https://angular.io/guide/http) 中所述
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 {}
但它会拦截来自我自己编写的服务和组件的 http 请求,但不会拦截由 angular.
对 html 模板发出的请求还有其他方法吗?
如果您可以访问 @angular/compiler
然后尝试覆盖 ResourceLoader
:
main.ts
platformBrowserDynamic([{
provide: COMPILER_OPTIONS,
useValue: { providers: [{
provide: ResourceLoader,
useClass: CustomResourceLoader,
deps: []
}]
},
multi: true
}]).bootstrapModule(AppModule);