ngOnInit 在 APP_INITIALIZER 完成之前启动 [英] ngOnInit starts before APP_INITIALIZER is done

查看:28
本文介绍了ngOnInit 在 APP_INITIALIZER 完成之前启动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

APP_INITIALIZER 运行一系列嵌套的 promise(我试过订阅,结果没有区别).

APP_INITIALIZER runs a series of nested promises (I've tried subscribes with no difference in the result).

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

The APP_INITIALIZER needs to get authenticated before it goes to retrieve data from the API server. It also needs to pull two tables from the API server (in sequence).

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

In api.service, http/get authorization happen in a promise. After the promise (then), I go to get data from the API service.

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

The issue is the component ngOnInit() - It attempts to get the variables before they exist.

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

I have tried the following code in the component, but all that does is call the initData() twice.

this.people = await this.apiService.initData();

api.service:

api.service:

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 完成之前运行的组件

the component that runs before APP_INITIALIZER is done

ngOnInit() {
    this.people = this.apiService.people;
    this.userName = this.apiService.userName;
      console.log("username");
      console.log(this.userName);
  }

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

I need to get the authorization before I can get data from the API server. I then need the data from the API server before I process the component.

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

I eventually get data, but not in time for the component.

推荐答案

APP_INITIALIZER 是在应用程序初始化之前调用的回调.所有注册的初始化器都可以选择返回一个 Promise.必须在引导应用程序之前解析所有返回 Promise 的初始化函数.

APP_INITIALIZER is a callback is invoked before an app is initialized. All registered initializers can optionally return a Promise. All initializer functions that return Promises must be resolved before the application is bootstrapped.

在您的情况下,您返回了一个承诺,但它几乎立即解决,因为您没有等待响应完成.你应该等待你的承诺,你可以通过 await 指令

In your case, you return a promise but it resolves almost immediately because you do not wait for the response to be finished. You should wait for your promises and you can do this by means of await directive

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;
    }

这篇关于ngOnInit 在 APP_INITIALIZER 完成之前启动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆