小编Chi*_*hip的帖子

ngOnInit 在 APP_INITIALIZER 完成之前启动

APP_INITIALIZER 运行一系列嵌套的承诺(我尝试过订阅,结果没有任何差异)。

APP_INITIALIZER 在从 API 服务器检索数据之前需要进行身份验证。它还需要从 API 服务器拉取两个表(按顺序)。

在 api.service 中,http/get 授权发生在一个承诺中。在承诺(then)之后,我去从API服务获取数据。

问题是组件 ngOnInit() - 它尝试在变量存在之前获取它们。

我已在组件中尝试了以下代码,但所做的只是调用 initData() 两次。

this.people = await this.apiService.initData();
Run Code Online (Sandbox Code Playgroud)

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;
    }
Run Code Online (Sandbox Code Playgroud)

应用程序模块

export function initData(appInitService: APIService) {
  return (): Promise<any> => { 
    return appInitService.initData();
  } …
Run Code Online (Sandbox Code Playgroud)

angular

4
推荐指数
1
解决办法
9105
查看次数

标签 统计

angular ×1