Ionic2:取消订阅事件以避免重复条目?

Ionic2: Unsubscribe Event to Avoid Duplicate Entries?

我已关注 this tutorial,其中概述了在 Ionic 2 应用程序中添加监控信标。我让它工作得很好:当视图加载时,它会初始化并开始侦听信标:

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 中创建一个函数以在视图退出之前调用,但我不知道如何防止 subscriptions/events 重复。

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

在您的情况下,您使用的是 Ionic 的 Events API which has its own 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);
    }