Angular 4:如何在订阅中使用等待/异步 [英] Angular 4 : How to use await/async within subscribe

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

问题描述

老实说,angular 中的 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.

因此在页面组件构造函数中,它使用可观察主题从信号器组件接收新数据,如下所示.

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() 基本上必须等待 this.SaveTableAsync 在开始之前完成.在这里可以实现await吗?提前谢谢你!!

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:如何在订阅中使用等待/异步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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