2017-05-09 36 views
1

我跟着this tutorial,它概述了在Ionic 2应用程序中添加监视信标。我有它工作的伟大:当视图加载时,它初始化并开始监听信标:Ionic2:取消订阅避免重复条目的事件?

home.ts

ionViewDidLoad() { 
     this.platform.ready().then(() => { 
      this.beaconProvider.initialise().then((isInitialised) => { 
       if (isInitialised) { 
        this.listenToBeaconEvents(); 
       } 
      }); 
     }); 
    } 

这将调用listenToBeaconEvents功能,填充列表视图中的所有的信标:

home.ts

listenToBeaconEvents() { 
     this.events.subscribe(‘didRangeBeaconsInRegion’, (data) => { 

      // update the UI with the beacon list 
      this.zone.run(() => { 

       this.beacons = []; 

       let beaconList = data.beacons; 
       beaconList.forEach((beacon) => { 
        let beaconObject = new BeaconModel(beacon); 
        this.beacons.push(beaconObject); 
       }); 

      }); 

     }); 
    } 

我能够停止使用this.beaconProvider.stopRanging(),从下面的函数调用的函数为:

信标provider.ts

stopRanging() { 
     if (this.platform.is('cordova')) { 
      // stop ranging 
      this.ibeacon.stopRangingBeaconsInRegion(this.region) 
       .then(
       () => { 
        console.log('Stopped Ranging'); 
       }, 
       error => { 
        console.error('Failed to stop monitoring: ', error); 
       } 
       ); 
     } 
    } 

我遇到的问题是这样的 - 在原来的教程信标列表显示在根,没有其他导航。我已经将它移到了不同​​的视图中,如果用户退出并重新进入视图,它会重新初始化并加载所有内容,导致重复的列表条目。

我试图在视图退出前调用beacon-provider.ts来调用函数,但我无法弄清楚如何保持订阅/事件不重复。

我试过this.delegate.didRangeBeaconsInRegion().unsubscribe()和其他一些变化,但它们都会导致运行时错误。

回答

2

在你的情况下,你正在使用Ionic的Events API,它有自己的unsubscribe(topic, handler)函数。

在您的组件,每当你需要退订,你应该用同一主题称之为:

this.events.unsubscribe(‘didRangeBeaconsInRegion’); 

这将删除所有处理您可能已经注册为didRangeBeaconsInRegion

如果您想取消订阅一个特定的功能,您必须注册一个指定的处理程序,您可以通过取消订阅进行发送。

this.events.unsubscribe(‘didRangeBeaconsInRegion’,this.mySubscribedHandler); 

而且你home.ts会是什么样子:

mySubscribedHandler:any = (data) => { 

      // update the UI with the beacon list 
      this.zone.run(() => { 

       this.beacons = []; 

       let beaconList = data.beacons; 
       beaconList.forEach((beacon) => { 
        let beaconObject = new BeaconModel(beacon); 
        this.beacons.push(beaconObject); 
       }); 

      }); 

     } 

    listenToBeaconEvents() { 
     this.events.subscribe(‘didRangeBeaconsInRegion’,this.mySubscribedHandler); 
    } 
+0

你能指定我宣布订阅类财产?我在'listenToBeaconEvents()',构造函数下的'export class TakeTour'内,以及beacon-provider.ts中都尝试过,但是我在这三者中都遇到了错误。谢谢! – Lauren

+0

你需要在你要订阅的类中声明它为一个类变量..记得也要从'rxjs/Subscription'中导入{Subscription {}};' –

+0

好吧,大部分错误都消失了,现在我只剩下一个:“Type'void'不可指定为'Subscription'类型,然后'this.beaconEventSubscription'突出显示为错误行。 我在订单的顶部导入了'Subscription',构造函数中的'public beaconEventSubscription:Subscription' 。 – Lauren