如何为所有延迟加载的模块提供自定义提供程序 [英] How to provide custom provider to the all lazy loaded modules
问题描述
我在我的应用程序中使用子组件的延迟加载策略.在应用程序的顶层,我具有自定义的HTTP提供程序,该提供程序可以拦截所有ajax调用.
I am using Lazy Loading strategy of subcomponents in my application. On the top level of application, I have custom HTTP provider which intercept all ajax calls.
providers:[{
provide: Http,
useFactory: (backend: XHRBackend, defaultOptions: RequestOptions, cookieService: CookieService) => new CustomHttp(backend, defaultOptions, cookieService),
deps: [XHRBackend, RequestOptions, CookieService]
}]
我的延迟加载模块不会影响此自定义提供程序.有没有办法为他们提供呢?在component.module文件的providers
属性中没有重复代码.谢谢!
My lazy loaded modules do not affect this custom provider. Is there a way to provide it for them too? Without duplication of code in the providers
property in the component.module file. Thank you!
推荐答案
我已经通过 @修复了它SkipSelf(). 每个延迟加载的模块都有自己的注入器,因此它对应用程序级别的扩展Http提供程序一无所知.当您在服务中注入Http provider时(在延迟加载的模块中),angular试图在模块的注入器中找到Http provider ...并从'@ angular/http'中找到原始的提供者.但是您需要找到在应用程序级别可见"的扩展Http提供程序. 因此,尝试在构造函数中的Http之前添加@SkipSelf():
I've fixed it with @SkipSelf(). Each lazy-loaded module has own injector, so it doesn't know anything about extended Http provider within an application level. While you're injecting Http provider in your services(in lazy-loaded modules) angular is trying to find Http provider in module's injector...and find the original one from '@angular/http'. But you need to find your extended Http provider which is 'visible' within application level. So try to add @SkipSelf() before Http in your constructor:
import { SkipSelf } from '@angular/core';
constructor(@SkipSelf() private http: Http) {
}
这篇关于如何为所有延迟加载的模块提供自定义提供程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!