我跟着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()
和其他一些變化,但它們都會導致運行時錯誤。
你能指定我宣佈訂閱類財產?我在'listenToBeaconEvents()',構造函數下的'export class TakeTour'內,以及beacon-provider.ts中都嘗試過,但是我在這三者中都遇到了錯誤。謝謝! – Lauren
你需要在你要訂閱的類中聲明它爲一個類變量..記得也要從'rxjs/Subscription'中導入{Subscription {}};' –
好吧,大部分錯誤都消失了,現在我只剩下一個:「Type'void'不可指定爲'Subscription'類型,然後'this.beaconEventSubscription'突出顯示爲錯誤行。 我在訂單的頂部導入了'Subscription',構造函數中的'public beaconEventSubscription:Subscription' 。 – Lauren