Skip to content

Instantly share code, notes, and snippets.

@kristofdegrave
Last active March 24, 2023 16:12
Show Gist options
  • Save kristofdegrave/518622c22c6bd6a65382d9365e965d84 to your computer and use it in GitHub Desktop.
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)
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);
}
}
@kristofdegrave
Copy link
Author

@arndwestermann No problem, code remains and is usable. Hopefully they provide an alternative solution that solves this issue

@jbezuk
Copy link

jbezuk commented Oct 18, 2021

Had the same problem, thanks for posting this!

@constantant
Copy link

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