ngOnInit 在 APP_INITIALIZER 完成之前启动

Chi*_*hip 4 angular

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();
  }
}
...
providers: [
    APIService,
    { provide: APP_INITIALIZER, useFactory: initData, deps: [APIService], multi: true }
  ],
Run Code Online (Sandbox Code Playgroud)

在 APP_INITIALIZER 完成之前运行的组件

ngOnInit() {
    this.people = this.apiService.people;
    this.userName = this.apiService.userName;
      console.log("username");
      console.log(this.userName);
  }
Run Code Online (Sandbox Code Playgroud)

我需要先获得授权才能从 API 服务器获取数据。然后,在处理组件之前,我需要来自 API 服务器的数据。

我最终得到了数据,但没有及时获取组件。

Ser*_*ell 5

APP_INITIALIZER是在应用程序初始化之前调用的回调。所有注册的初始值设定项都可以选择返回 Promise。所有返回 Promise 的初始化函数都必须在应用程序引导之前解析。

在您的情况下,您返回一个承诺,但它几乎立即解决,因为您不等待响应完成。你应该等待你的承诺,你可以通过await指令来做到这一点

async initData(): Promise<Person[]> {
        this.userData$ = this.http.get('/.auth/me', {observe: 'response'});
        await this.userData$.toPromise().then(async res => {
          this.resBody = res.body;
          this.token = res.body[0].access_token;
          return await this.getLegalSub(this.legalsubdeptsURL)
            .toPromise().then(async legalsubdepts => {
              this.legalsubdepts = legalsubdepts;
              return await this.getPeopleData(this.personURL)
              .toPromise().then(people => {
                this.people = people;
                return this.people;
              });
            });
        });
      }
      return this.people;
    }
Run Code Online (Sandbox Code Playgroud)

  • 为什么会这样,你能解释得更详细一些吗? (2认同)