Async request is done after view is loaded

So I got a async problem. I get a list of soccer games which of course contains 2 teams ea. I’m trying to get the team logo’s trough a seperate API call but after that call is done the view is already loaded.

(I do get the logo url’s in the console since they come in after view is loaded)

/**
     * Process the data from the request.
     */
    processData(data) {

        for (let i = 0; i < data.length; i++) {

            data[i].divider = this.addMonthDivider(data[i].date);
            data[i].today = this.isDateToday(data[i].date);

            data[i].logo = [];

            data[i].logo[0] = this.getTeamLogo(data[i].teams[0]);
            data[i].logo[1] = this.getTeamLogo(data[i].teams[1]);
}
        this.games = data;
}
/**
     * Get team logo
     */
    getTeamLogo(teamID) {
        if (teamID == '237' || teamID == '12227') {
            return 'assets/img/nec.svg';
        } else {
            this.httpProvider
                .getData('https://www.url=' + teamID)
                .subscribe(
                    (data: object) => {
                        if (data[0]) {
                            console.log(data[0].source_url);
                            return data[0].source_url;
                        }
                    });
        }
    }

Can anyone help me?

Fixed it by using promises.

Share the fixed code please for other users.

 this.getTeamLogo(data[i].teams[0]).then(res => {
                data[i].logo[0] = res;
            });
            this.getTeamLogo(data[i].teams[1]).then(res => {
                data[i].logo[1] = res;
            });

/**
     * Get team logo
     */
    getTeamLogo(teamID) {
        return new Promise(resolve => {
            if (teamID == '237' || teamID == '12227') {
                resolve('assets/img/nec.svg')

            } else {
                this.httpProvider
                    .getData('https://www.url=' + teamID)
                    .subscribe(
                        (data: object) => {
                            if (data[0]) {
                                resolve(data[0].source_url)
                            }
                        });
            }
        })

    }
1 Like

The above post demonstrates the explicit promise construction antipattern. I don’t like the magic numbers either, but assuming they’re unavoidable, I would prefer:

getTeamLogo(teamId: string): Promise<string> {
  let rv: Promise<string>;
  if (teamId == '237' || teamId == '12227') {
    rv = Promise.resolve('assets/img/nec.svg');
  } else {
    rv = this.httpProvider.getData('https://www.url=' + teamId)
      .map(rsp => rsp[0] ? rsp[0].source_url : 'assets/img/fallback.svg')
      .toPromise();
  }
  return rv;
}   

A post was split to a new topic: Promise failing in case of a call to @JavascriptInterface method