ionic3 之 事件Events使用

一、案例描述

保存完之后使用this.navCtrl.pop()进行跳转到详情页,但是不请求调用详情的接口,导致保存完的数据无法更新

二、 事件Events的介绍

事件注册 在任意一界面注册事件之后可在任意界面根据事件名称进行调用。

Events 有三个方法 分别是:
this.events.publish () //注册Events事件
this.events.subscribe() //调用Events事件
this.events.unsubscribe() //注销Events事件

三、事件Events及解决办法

在请求保存接口之后注册一个事件
B页面注册一个事件,A页面调用该事件
在这里插入图片描述
然后在跳转的详情页面调用该事件,注意先引用一下events
在这里插入图片描述

四、案例代码

B页面注册一个事件


import { IonicPage, NavController, NavParams ,Events} from 'ionic-angular';

export class BusinessPressRecordPage {

   constructor( public loading: Loading, public events: Events  ){

   }
// 保存
saveBtn(){
  this.loading.show();
  this.urgeService.postSaveUrge(params).subscribe(resp => {
      this.loading.hide();
      this.navCtrl.pop();
      this.events.publish('businessDetail:created')   // 注册事件
    })
}
}

A页面调用该事件

import { IonicPage, NavController, NavParams ,Events} from 'ionic-angular';

export class BusinessPressRecordPage {

   constructor( public loading: Loading, public events: Events  ){
       events.subscribe('businessDetail:created', (data) => {

           this.getUrgeDetail()   //调用详情事件,重新更新数据

       });
   }
}

五、注意事项

Events不使用时尽量进行销毁,特别是放在页面事件中的,可能会反复注册事件,如果一定要保留监听可以考虑将注册方法写在constructor()中(constructor()只有在页面初始化的时候执行一次)。

猜你喜欢

转载自blog.csdn.net/qq_39490750/article/details/117021835