import { BrowserModule } from ‘@angular/platform-browser‘;
import { NgModule, APP_INITIALIZER } from ‘@angular/core‘;
import { AppComponent } from ‘./app.component‘;
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [
{
provide: APP_INITIALIZER,
useFactory: initApp,
deps: [HttpClient],
multi: true
}
],
bootstrap: [AppComponent]
})
export class AppModule { }
下面我们看initApp的定义,注意一定要是返回值为Promise的函数
简单的一个Projmise例子
export function initApp() {
return () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(‘In initApp‘);
resolve(); //reject() 就会终止程序的启动
}, 3000);
});
};
}
获取一种信息
export function initApp(http: HttpClient) {
return () => {
return http.get(‘https://api.github.com/users/sagar-ganatra‘)
.toPromise()
.then((resp) => {
console.log(‘Response 1 - ‘, resp);
});
};
}
登录后获取一种信息
export function initApp(http: HttpClient) {
return () => {
return http.get(‘login‘).toPromise()
.then((resp) => {
this.user = resp.user;
return this.http.get(‘fileInfo‘).toPromise();
});
};
}