Problem:
I am setting up lazy loading for non-routed module in angular. At version 7 I used NgModuleFactoryLoader
and it's function load
to lazy load module and get first entry point to the module (service in out case)
this.loader.load('path-to-module')
.then(factory => {
const module = factory.create(this._injector);
return module.injector.get(EntryService);
});
But in Angular 8 NgModuleFactoryLoader
is deprecated so instead I have to load module in that way:
import('path-to-module')
.then(m => m.MyModule)
.then(myModule => {
...
});
The problem here that I can not retrieve factory and get provider here in a new lazy loading (one of ideas of IVY - no factories).
What I have already tried:
First solution (work only with JIT compiler which is not suits us as I am using AOT compiler for prod)
import('path-to-module')
.then(m => m.MyModule)
.then(myModule => {
return this._compiler.compileModuleAsync(myModule)
.then(factory => {
const module = factory.create(this._injector);
return module.injector.get(EntryService);
});
});
Second solution (dirty and not fully checked. It is using ngInjectorDef
which is new feature of IVY and has no any described API yet):
import('path-to-module')
.then(m => m.MyModule)
.then(myModule => {
const providers = myModule['ngInjectorDef'].providers; // Array<Providers>
... find EntryService in providers
});
ngInjectorDef
- is a static module class property which is added by angular and has properties factory, providers and imports.
Sources:
- https://netbasal.com/the-need-for-speed-lazy-load-non-routable-modules-in-angular-30c8f1c33093 (lazy loading non routable modules till angular 8)
- https://herringtondarkholme.github.io/2018/02/19/angular-ivy/ (IVY preview - see section
No NgFactory file anymore
) - https://blog.angularindepth.com/automatically-upgrade-lazy-loaded-angular-modules-for-ivy-e760872e6084 (Describes differences between lazy loading in Angular < 8 and Angular 8. Important section - From NgModule to NgModuleFactory with the AOT Compiler, what is basically my problem now)