How to provide custom provider to the all lazy loa

2019-04-27 04:38发布

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条回答
smile是对你的礼貌
2楼-- · 2019-04-27 05:18

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) {
}
查看更多
登录 后发表回答