本文介绍了如何在Angular 4.3.5中拦截对组件html模板的请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要拦截对html组件模板的请求。 Angular版本是 4.3.5

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

我尝试通过实现拦截器来实现它,如《角度httpClient手册》( )

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

interceptor.service.js

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

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模板的请求。

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.

还有其他方法吗?

推荐答案

如果您可以访问 @ angular / compiler ,请尝试覆盖 ResourceLoader

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

这篇关于如何在Angular 4.3.5中拦截对组件html模板的请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 15:01