-
Notifications
You must be signed in to change notification settings - Fork 24.8k
/
application_init.ts
88 lines (77 loc) 路 2.34 KB
/
application_init.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/**
* @license
* Copyright Google LLC 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 {Inject, Injectable, InjectionToken, Optional} from './di';
import {isPromise} from './util/lang';
import {noop} from './util/noop';
/**
* A [DI token](guide/glossary#di-token "DI token definition") that you can use to provide
* one or more initialization functions.
*
* The provided functions are injected at application startup and executed during
* app initialization. If any of these functions returns a Promise, initialization
* does not complete until the Promise is resolved.
*
* You can, for example, create a factory function that loads language data
* or an external configuration, and provide that function to the `APP_INITIALIZER` token.
* The function is executed during the application bootstrap process,
* and the needed data is available on startup.
*
* @see `ApplicationInitStatus`
*
* @publicApi
*/
export const APP_INITIALIZER = new InjectionToken<Array<() => void>>('Application Initializer');
/**
* A class that reflects the state of running {@link APP_INITIALIZER} functions.
*
* @publicApi
*/
@Injectable()
export class ApplicationInitStatus {
private resolve = noop;
private reject = noop;
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;
}
}