Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

async/await prevents Angular2 from rendering the component when used in template statement

The following method will be executed when clicking a button of a component.

async onClickButton() {
    await this.shoppingCartService.add(this.selectedOffer);
    this.router.navigate(['ShoppingCartComponent']);
}

The data will be added to the shopping cart, but upon navigating to the next page only the title will be rendered, the data won't. This method works and the following page will correctly be rendered if not using async-await. Forcing change detection with ChangeDetectorRef.detectChanges() and ApplicationRef.tick() have no effect. After leaving the next page i.e. ShoppingCartComponent the rendering takes place and for a moment the data will be displayed. Any ideas what could go wrong?

like image 742
Andras Hatvani Avatar asked Mar 23 '16 06:03

Andras Hatvani


1 Answers

This is a known issue of async/await. It causes code following await not to run inside Angulars zone.

As workaround you would need to inject NgZone in the constructor and change your code to

async onClickButton() {
    await this.shoppingCartService.add(this.selectedOffer);
    this.ngZone.run(() => {
      this.router.navigate(['ShoppingCartComponent']);
    });
}

See also https://github.com/angular/angular/issues/322

like image 97
Günter Zöchbauer Avatar answered Nov 15 '22 06:11

Günter Zöchbauer