从呈现组件中的模板语句中使用时,异步/的await prevents Angular2 [英] async/await prevents Angular2 from rendering the component when used in template statement

查看:106
本文介绍了从呈现组件中的模板语句中使用时,异步/的await prevents Angular2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

点击的部件的按钮时,下面的方法将被执行。

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']);
}

中的数据将被添加到购物车中,但在导航到下一个页面只有标题将被渲染,数据不会。这种方法可行,以下页面将正确地如果不使用异步的await呈现。
强制与ChangeDetectorRef.detectChanges变化检测()和ApplicationRef.tick()没有任何效果。
离开下页即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?

推荐答案

这是的异步的已知问题 / 等待。它会导致code以下的await 不Angulars区域中运行。

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

至于解决方法,你将需要注入 NgZone 在构造函数和改变你的code到

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']);
    });
}

另请参阅 https://github.com/angular/angular/issues/322

这篇关于从呈现组件中的模板语句中使用时,异步/的await prevents Angular2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆