'Angular: Lazy-Loading Module not calling InjectionToken factory
I am trying to provide the APP_BASE_HREF injection token in a Lazy-Loading Module,
however, the factory method is not called at all.
Here https://github.com/MaurizioCasciano/Angular-Lazy-Injection/branches you can find the corresponding minimal project, with two separated branches:
- app-provider-root (working custom APP_BASE_HREF)
- lazy-provider-root (not working custom APP_BASE_HREF)
You can also try the two branches on StackBlitz:
- https://stackblitz.com/github/MaurizioCasciano/Angular-Lazy-Injection/tree/app-provider-root
- https://stackblitz.com/github/MaurizioCasciano/Angular-Lazy-Injection/tree/lazy-provider-root
If I move the same code snippet to the static AppModule it gets called as expected.
providers: [
{
provide: APP_BASE_HREF,
useFactory: appBaseHrefFactory
}
]
export function appBaseHrefFactory() {
console.log("APP MODULE window.location.pathname: " + window.location.pathname);
return window.location.pathname;
}
How can I force the APP_BASE_HREF to be provided also from the Lazy-Loading module?
Update
If I inject the value in the module constructor, the factory method gets called, but the value is not picked up by the imported module/service.
export class RemoteModule {
constructor(@Inject(APP_BASE_HREF) private apipBaseHref: string) {
console.log("Remote APP BASE HREF: " + appBaseHref);
}
}
Solution 1:[1]
If you provide any token, like APP_BASE_HREF, or any other in the current module, - this token will be available only for this module and its children. Not for any other.
To solve your case you can add some kind of state, for example with service:
@Injectable({
providedIn: 'root'
})
export class BaseHrefValueService extends BehaviorSubject<string> {
}
Create reusable provider, just to DRY:
export const APP_BASE_HREF_PROVIDER = {
provide: APP_BASE_HREF,
useFactory: (service) => {
if (!service.value) {
service.next(window.location.pathname);
}
return service.value;
},
deps: [BaseHrefValueService]
}
And then inject it in any lazy modules:
@NgModule({
...
providers: [APP_BASE_HREF_PROVIDER],
})
export class YourModule {}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
