Skip to content

Instantly share code, notes, and snippets.

@kristofdegrave
Last active March 24, 2023 16:12
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • 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);
}
}
@arndwestermann
Copy link

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!

@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