【问题标题】:await function on ngOnInit returning undefinedngOnInit 上的 await 函数返回未定义
【发布时间】:2021-05-11 02:10:03
【问题描述】:

我试图在执行其他函数之前获取特定数据,因为其他函数依赖于该函数来分配变量,但刷新时出现未定义错误,但如果我导航到我需要的位置,它不会抛出未定义错误,这是我的代码:

public async ngOnInit() {
    const getdata = await this.websiteSettingsService.webConfig;
    this.getId(getdata);
    this.TournamentDetails = this.tournamentService.getMainTournamentDetails(this.leaderboardId).pipe(
      takeUntil(this.unsubscribe),
      shareReplay(1)
    );

    this.TournamentDetails.subscribe((response) => {
      this.getTournamentDetails(response);
    });
    }
  public getTournamentDetails(response: TournamentStatusModel) {
    this.TournamentStatus = response;

  }

  public getId(response: any) {
    response.forEach((ID) => {
      if (ID.settingName.includes('current_tournament')) {
        this.leaderboardId = ID.value;
      }
    });
  }

错误出现在我的 getId 函数中,说 TypeError: can't access property "forEach", response is undefined

但我首先在等待数据,所以我很困惑它为什么这样做

【问题讨论】:

  • 你能给我们看看 webisteSettingsService 代码吗?

标签: angular async-await


【解决方案1】:

我认为你可以尝试这样的事情。在 ngOnInit 中声明你的异步函数,然后立即调用它。

public ngOnInit() {
    (async () => {
        const getdata = await this.websiteSettingsService.webConfig;
        this.getId(getdata);
        this.TournamentDetails = this.tournamentService.getMainTournamentDetails(this.leaderboardId).pipe(
            takeUntil(this.unsubscribe),
            shareReplay(1)
        );

        this.TournamentDetails.subscribe((response) => {
            this.getTournamentDetails(response);
        });
    })();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-21
    • 1970-01-01
    • 2019-01-10
    • 1970-01-01
    • 1970-01-01
    • 2020-06-07
    相关资源
    最近更新 更多