Async request is done after view is loaded

#1

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?

#2

Fixed it by using promises.

#3

Share the fixed code please for other users.

#4
 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
#5

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;
}   
split this topic #6

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