APP_INITIALIZER 运行一系列嵌套的承诺(我尝试过订阅,结果没有任何差异)。
APP_INITIALIZER 在从 API 服务器检索数据之前需要进行身份验证。它还需要从 API 服务器拉取两个表(按顺序)。
在 api.service 中,http/get 授权发生在一个承诺中。在承诺(then)之后,我去从API服务获取数据。
问题是组件 ngOnInit() - 它尝试在变量存在之前获取它们。
我已在组件中尝试了以下代码,但所做的只是调用 initData() 两次。
this.people = await this.apiService.initData();
api.服务:
async initData(): Promise<Person[]> {
this.userData$ = this.http.get('/.auth/me', {observe: 'response'});
this.userData$.toPromise().then( res => {
this.resBody = res.body;
this.token = res.body[0].access_token;
this.getLegalSub(this.legalsubdeptsURL)
.toPromise().then(legalsubdepts => {
this.legalsubdepts = legalsubdepts;
this.getPeopleData(this.personURL)
.toPromise().then(people => {
this.people = people;
return this.people;
});
});
});
}
return this.people;
}
应用程序模块
export function initData(appInitService: APIService) {
return (): Promise<any> => {
return appInitService.initData();
}
}
...
providers: [
APIService,
{ provide: APP_INITIALIZER, useFactory: initData, deps: [APIService], multi: true }
],
在 APP_INITIALIZER 完成之前运行的组件
ngOnInit() {
this.people = this.apiService.people;
this.userName = this.apiService.userName;
console.log("username");
console.log(this.userName);
}
我需要先获得授权才能从 API 服务器获取数据。
然后,在处理组件之前,我需要来自 API 服务器的数据。
我最终得到了数据,但没有及时获取组件。