angular-cn/packages/core/src/application_init.ts
mhartington 2b6e1f0f4b docs(core): remove experimental tag (#24032)
Remove experimental note on APP_INITIALIZER.

PR Close #24032
2018-08-01 10:56:06 -07:00

69 lines
1.7 KiB
TypeScript

/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {isPromise} from '../src/util/lang';
import {Inject, Injectable, InjectionToken, Optional} from './di';
/**
* A function that will be executed when an application is initialized.
*/
export const APP_INITIALIZER = new InjectionToken<Array<() => void>>('Application Initializer');
/**
* A class that reflects the state of running {@link APP_INITIALIZER}s.
*/
@Injectable()
export class ApplicationInitStatus {
// TODO(issue/24571): remove '!'.
private resolve !: Function;
// TODO(issue/24571): remove '!'.
private reject !: Function;
private initialized = false;
public readonly donePromise: Promise<any>;
public readonly done = false;
constructor(@Inject(APP_INITIALIZER) @Optional() private appInits: (() => any)[]) {
this.donePromise = new Promise((res, rej) => {
this.resolve = res;
this.reject = rej;
});
}
/** @internal */
runInitializers() {
if (this.initialized) {
return;
}
const asyncInitPromises: Promise<any>[] = [];
const complete = () => {
(this as{done: boolean}).done = true;
this.resolve();
};
if (this.appInits) {
for (let i = 0; i < this.appInits.length; i++) {
const initResult = this.appInits[i]();
if (isPromise(initResult)) {
asyncInitPromises.push(initResult);
}
}
}
Promise.all(asyncInitPromises).then(() => { complete(); }).catch(e => { this.reject(e); });
if (asyncInitPromises.length === 0) {
complete();
}
this.initialized = true;
}
}