Angular 4:如何在subscribe中使用await / async [英] Angular 4 : How to use await/async within subscribe

查看:2831
本文介绍了Angular 4:如何在subscribe中使用await / async的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以诚实地说,角度中的等待/异步真的是一个很棒的东西,它减少了很多大括号,提高了可读性并防止了很多人为错误。然而,有一件事困扰了我很多。如何在订阅中使用await / async。

I can honestly say await/async in angular is really a great stuff, it reduces a lot of braces, improves readability and prevent a lot of human error. However, one thing puzzles me a lot. how can I use await/async inside subscribe.

让我们说

 @Injectable()
export class TableCom extends BaseCom {
  public subject = new Subject<any>();

}

TableCom是一个提供者,充当信号器组件之间的通信器和页面组件。

TableCom is a provider serves as a communicator between a signalr component and a page component.

所以在页面组件构造函数中,它使用可观察主题从signalr组件接收新数据,如下所示。

so inside the page component constructor, it is using the observable subject to receive new data from signalr component as shown below.

constructor(protected nav: NavController,
        protected db: Storage,
        protected alert: AlertController,
        protected order: OrderData,
        protected translate: TranslateService,
        public navParams: NavParams,
        public toastCtrl: ToastController,
        private table_data: TableData,
        private load: LoadingController,
        private http: Http,
        private com_table: TableCom

    )
    {
        super(nav, db, alert, order, translate, undefined, false);
        this.previous_page = navParams.get('previous_page');
        this.subscribe_table = this.com_table.Receive().subscribe(res =>
        {
            await this.SaveTableAsync(res.data);
            this.ReadTableAsync();
        });
    }

问题是this.ReadTableAsync()基本上必须等待这个。 SaveTableAsync在开始之前完成。等待可以在这里实现吗?提前谢谢!!

the issue is that the this.ReadTableAsync() basically has to wait this.SaveTableAsync to be finished before starting. await can be achieved here ? thank you in advance !!

推荐答案

您需要 async 关键字将该函数标记为async:

You need the async keyword to mark the function as "async":

this.subscribe_table = this.com_table.Receive().subscribe(async res => {
    await this.SaveTableAsync(res.data);
    this.ReadTableAsync();
});

这篇关于Angular 4:如何在subscribe中使用await / async的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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