Last active
March 24, 2023 16:12
-
-
Save kristofdegrave/518622c22c6bd6a65382d9365e965d84 to your computer and use it in GitHub Desktop.
NgModuleFactory that can handle ModuleWithProviders in a lazy loaded context (https://github.com/angular/angular/issues/34351)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class LazyNgModuleWithProvidersFactory<T> extends NgModuleFactory<T> { | |
constructor(private moduleWithProviders: ModuleWithProviders<T>) { | |
super(); | |
} | |
get moduleType() { | |
return this.moduleWithProviders.ngModule; | |
} | |
create(parentInjector: Injector | null) { | |
const injector = Injector.create({ | |
providers: this.moduleWithProviders.providers as StaticProvider[], | |
parent: parentInjector | |
}); | |
const compiler = injector.get(Compiler); | |
const factory = compiler.compileModuleSync(this.moduleType); | |
return factory.create(injector); | |
} | |
} |
@arndwestermann No problem, code remains and is usable. Hopefully they provide an alternative solution that solves this issue
Had the same problem, thanks for posting this!
NgModuleFactory
is deprecated https://angular.io/api/core/NgModuleFactory
I use this code:
import { ModuleWithProviders, NgModule, Type } from '@angular/core';
export function utilsConfigureLazyModule<T>(moduleWithProviders: ModuleWithProviders<T>): Type<T> {
const { ngModule, providers } = moduleWithProviders;
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore todo: https://stackoverflow.com/a/59687799/2331113
const injections: NgModule = ngModule['ɵinj'];
if (injections && providers) {
injections.providers?.push(...providers)
}
return ngModule;
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you so much for that, i just stumbled upon this problem! Unfortunately too late for the voting on the issue, altho i don't think my vote would've made a difference. Anyway, big thanks for that!