Async / await prevents Angular2 from rendering the component when used in a template instruction

When a component button is clicked, the following method is executed.

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

The data will be added to the shopping cart, but when you go to the next page, only the header will be displayed, the data will not be. This method works, and the next page will display correctly if you do not use async-wait. Force change detection using ChangeDetectorRef.detectChanges () and ApplicationRef.tick () is not affected. After exiting the next page, i.e. ShoppingCartComponent, the rendering is performed, and for a moment the data will be displayed. Any ideas what could go wrong?

+6
source share
1 answer

This is a known async / await problem. This causes the code following await to not run inside the corner zone.

As a workaround, you will need to enter NgZone in the constructor and change the 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

+9
source

All Articles