Skip to content

Instantly share code, notes, and snippets.

@ghetolay
Created January 30, 2018 10:04
Show Gist options
  • Save ghetolay/4f7e0f1314860917fe1bea62e59ac233 to your computer and use it in GitHub Desktop.
Save ghetolay/4f7e0f1314860917fe1bea62e59ac233 to your computer and use it in GitHub Desktop.
Ensure Singleton Provider (AOT compatible)
export function singletonFactory<T>(token: InjectionToken<T>, factory: Function, deps: any[], fnToken = new InjectionToken('')) {
return [
{
provide: fnToken,
useValue: factory
},
{
provide: token,
deps: [[new SkipSelf(), new Optional(), token], fnToken, ...(deps ? deps : [])],
useFactory: function(parent: T | null, factoryFn: Function, ...args) {
if (parent != null) return parent;
factoryFn.apply(null, args);
}
}
];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment