问题
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