2017-05-09 66 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