Skip to content

Instantly share code, notes, and snippets.

@UserGalileo
Last active December 13, 2018 18:41
Show Gist options
  • Save UserGalileo/ab3b2908a8cd4401ee6573cd12e10832 to your computer and use it in GitHub Desktop.
Save UserGalileo/ab3b2908a8cd4401ee6573cd12e10832 to your computer and use it in GitHub Desktop.
Angular - InstantiatorModule
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
}
]
}
}
}
...
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