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

Lau*_*ren 2 ibeacon ionic-framework ionic2

我已经按照本教程概述了在Ionic 2应用程序中添加监控信标.我有它工作得很好:当视图加载时,它初始化并开始监听信标:

home.ts

    ionViewDidLoad() {
        this.platform.ready().then(() => {
            this.beaconProvider.initialise().then((isInitialised) => {
                if (isInitialised) {
                    this.listenToBeaconEvents();
                }
            });
        });
    } 
Run Code Online (Sandbox Code Playgroud)

这将调用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);
                });

            });

        });
    }
Run Code Online (Sandbox Code Playgroud)

我可以使用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);
                }
                );
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

我已经尝试在beacon-provider.ts中创建一个函数,在视图退出之前调用,但我无法弄清楚如何保持订阅/事件不会重复.

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

Sur*_*Rao 10

在您的情况下,您正在使用具有自己功能的Ionic 事件 API unsubscribe(topic, handler).

在您的组件中,无论何时需要取消订阅,都应使用相同的主题调用它:

this.events.unsubscribe(‘didRangeBeaconsInRegion’);
Run Code Online (Sandbox Code Playgroud)

这将删除您可能已注册的所有处理程序didRangeBeaconsInRegion.

如果要取消订阅某个特定功能,则必须注册一个可以通过取消订阅发送的命名处理程序.

this.events.unsubscribe(‘didRangeBeaconsInRegion’,this.mySubscribedHandler);
Run Code Online (Sandbox Code Playgroud)

你的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);
    }
Run Code Online (Sandbox Code Playgroud)