ngOnInit 在 APP_INITIALIZER 完成之前启动

2024-03-30

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 服务器的数据。

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


APP_INITIALIZER https://angular.io/guide/dependency-injection-providers#predefined-tokens-and-multiple-providers是在应用程序初始化之前调用的回调。所有注册的初始值设定项都可以选择返回 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;
    }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ngOnInit 在 APP_INITIALIZER 完成之前启动 的相关文章

随机推荐