angular - ionic 事件触发次数过多。每次触发时加一?

标签 angular ionic-framework socket.io ionic2 ionic3

TL;DR:订阅事件触发了太多次。

我设置了一个事件,当实时数据通过套接字传入时,该事件会被触发。

通过控制台日志我发现,实时数据正确地只输入一次。被触发的事件,当实时数据进来时,也只被触发一次:

console.log("Event publish got fired!");
this.events.publish(EVENTSLUG_STAMP_UPDATE);

每次收到数据时我只看到一次这个控制台日志。

奇怪的部分来了:订阅事件触发了多次!每次实时数据进来,它都会触发一次。

this.events.subscribe(EVENTSLUG_STAMP_UPDATE, () => {
  console.log("Event gets gets handled!");
  // Do some code here. This code gets done to many times.
});

我看到第一次实时数据进来了:

Event publish got fired!
Event gets gets handled!

在控制台中。第二次,我明白了

Event publish got fired!
Event gets gets handled!
Event gets gets handled!

第三次看到:

Event publish got fired!
Event gets gets handled!
Event gets gets handled!
Event gets gets handled!

等等。我正在使用 socket.io 获取实时数据。但正如我所说,用控制台日志填充我的代码我得出的结论是,只有订阅事件会触发多次。每次事件再次发布时递增 1。

编辑

我找到了一个可行的解决方法:

this.events.subscribe(EVENTSLUG_STAMP_UPDATE, () => {
  this.navCtrl.setRoot('ScanSuccessPage').then(() => {
    this.events.unsubscribe(EVENTSLUG_STAMP_UPDATE);
  });
});

最佳答案

所以我也花了一点时间来解决这个问题。对我来说,最终结果是我在一个组件上有 subscribe(),当我在应用程序中导航时,该组件正在被销毁并重新创建,但我没有 OnDestroy组件上的事件处理程序带有 unsubscribe(),因此每次实例化时都会添加另一个订阅处理程序。

注意:您还必须将相同 事件处理程序传递给unsubscribe(),参见Ionic2: Unsubscribe Event to Avoid Duplicate Entries?

关于angular - ionic 事件触发次数过多。每次触发时加一?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49047257/

相关文章:

Angular2 设置代理失败

css - 抽屉侧菜单内容区域内状态转换的 ionic 奇怪行为

javascript - socket.io SERVER 是否发出回调阻塞?

javascript - Socket.io 未在握手中发送 cookie,导致请求停止

ios - Websockets 在 iOS 和 Safari 上不起作用 - OSSStatus 错误 9837

Java : Cannot send a form with Angular 5 that contain an input of type file to a REST backend (Spring Boot)

javascript - Ionic 2/Angular 2 中的 Mapbox 标记单击事件

html - 自定义库组件不是已知元素,但应用程序编译并运行

angular - 为 ionic 3 添加 javascript 虚拟摇杆

Android webview 渲染不好