Last active
December 13, 2018 18:41
-
-
Save UserGalileo/ab3b2908a8cd4401ee6573cd12e10832 to your computer and use it in GitHub Desktop.
Angular - InstantiatorModule
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
import { NgModule, ModuleWithProviders, InjectionToken, Inject, Injector } from '@angular/core'; | |
import { CommonModule } from '@angular/common'; | |
export const INSTANTIATED_SERVICES = new InjectionToken<any[]>('instantiated services'); | |
/** | |
* This module takes an array of services | |
* and instantiates them for you. They'll be | |
* singletons for the injector of the importing module. | |
* | |
* Useful if you need services to run without | |
* putting them in your components' contructors. | |
*/ | |
@NgModule({ | |
imports: [ CommonModule ] | |
}) | |
export class InstantiatorModule { | |
constructor( | |
@Inject(INSTANTIATED_SERVICES) services: any[], | |
injector: Injector | |
) { | |
services.forEach(service => { | |
injector.get(service.provide || service) | |
}) | |
} | |
static register(services: any[]): ModuleWithProviders { | |
return { | |
ngModule: InstantiatorModule, | |
providers: [ | |
...services, | |
{ | |
provide: INSTANTIATED_SERVICES, | |
useValue: services | |
} | |
] | |
} | |
} | |
} |
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
... | |
const services = [ FirstService, SecondService ]; | |
@NgModule({ | |
imports: [ | |
... | |
InstantiatorModule.register(services) | |
] | |
}) | |
export class YourModule {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment