Skip to content

Instantly share code, notes, and snippets.

@0xMatt
Last active March 26, 2017 19:15
Show Gist options
  • Save 0xMatt/62aa853f1ef1c838f5a3b895b4e21458 to your computer and use it in GitHub Desktop.
Save 0xMatt/62aa853f1ef1c838f5a3b895b4e21458 to your computer and use it in GitHub Desktop.
OBJECTS is empty when compiled but when via ng serve
import {OBJECTS} from './my.token.ts';
@Injectable()
export class MyInitializer {
constructor(private injector: Injector) {
}
appInitializer(): Promise<any> {
const p: Promise<any> = this.injector.get(LOCATION_INITIALIZED, Promise.resolve(null));
return p.then(() => {
let resolve: Function = null;
const res = new Promise(r => resolve = r);
const router = this.injector.get(Router);
const objects = this.injector.get(OBJECTS)
console.log('objects', objects);
return res;
});
}
bootstrapListener(bootstrappedComponentRef: ComponentRef<any>): void {
const ref = this.injector.get(ApplicationRef);
if (bootstrappedComponentRef !== ref.components[0]) {
return;
}
}
}
export function getAppInitializer(r: MyInitializer) {
return r.appInitializer.bind(r);
}
export function getBootstrapListener(r: MyInitializer) {
return r.bootstrapListener.bind(r);
}
// This shouldn't be called until the app is bootstrapped
export const MY_INITIALIZER =
new InjectionToken<(compRef: ComponentRef<any>) => void>('My Initializer');
export function provideMyInitializer() {
return [
MyInitializer,
{
provide: APP_INITIALIZER,
multi: true,
useFactory: getAppInitializer,
deps: [MyInitializer]
},
{provide: MY_INITIALIZER, useFactory: getBootstrapListener, deps: [MyInitializer]},
{provide: APP_BOOTSTRAP_LISTENER, multi: true, useExisting: MY_INITIALIZER},
];
}
import {provideMyInitializer} from './my-initializer.ts';
import {OBJECTS} from './my.token.ts';
export class MyModule {
/**
*
* @param provider
* @returns {{ngModule: MyModule, providers: [any]}}
*/
public static forRoot(provider: MyProvider): ModuleWithProviders {
return {
ngModule: MyModule,
providers: [
provideObjects(provider.objects), // this is just an arary of instantiated objects
provideMyInitializer()
]
};
}
}
/**
*
* @param admins
*/
export function provideObjects(objects: Array<Object>): Array<Provider> {
return [
{provide: OBJECTS, multi: true, useValue: objects}
];
}
export const OBJECTS = new InjectionToken<Object[][]>('OBJECTS');
@0xMatt
Copy link
Author

0xMatt commented Mar 26, 2017

Line 16 in my.initializer.ts is what's empty when compiled but contains the expected objects via ng serve.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment