How to provide custom provider to the all lazy loaded modules

笑着哭i 提交于 2019-12-07 01:22:45

问题


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]
    }]

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!


回答1:


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) {
}


来源:https://stackoverflow.com/questions/40873480/how-to-provide-custom-provider-to-the-all-lazy-loaded-modules

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