【问题标题】:ionic2 - Device Motion returning observable but unsubscribe gives errorionic2 - 设备运动返回可观察但取消订阅给出错误
【发布时间】:2016-04-17 04:05:48
【问题描述】:

我正在尝试使用 ionic2 检测运动。 这是我的 detectMotion.ts 的 sn-p。

import {DeviceMotion} from 'ionic-native';
@Page({
    templateUrl: 'build/pages/pedometer/pedometer.html'
})
export class Pedometer {
   platform;
   watch;
   constructor () {
        this.platform = platform;
   }
   startWatching() {
       console.log('Starting to watch');
       this.watch = DeviceMotion.watchAcceleration(this.options);
       this.watch.subscribe(result => {this.detectMotion(result)});
   }
   stopWatching() {
       console.log('Stop Watching');
       // this.watch.dispose();
       this.watch.unsubscribe();
       // this.watch.clearWatch();
   }
   detectMotion(result) {
       console.log('Current Readings: '+ JSON.stringify(result) );
       //.....do something with the results.....
       this.stopWatching(); // Stop and wait for a second before restarting
       setTimeout(this.startWatching(), 1000);
   }
}

在 html 中单击按钮时会调用 StartWatching。 我已经尝试了我可以研究的所有 3 个选项。退订;处置;清除手表 但一切都是徒劳的。我得到的确切错误是

error    ORIGINAL EXCEPTION: TypeError: Object #<Observable> has no method 'unsubscribe'

从 ioni2 的 reference 我了解到它返回一个 Observable

感谢任何帮助或指针 提前致谢

~达瓦尔

【问题讨论】:

    标签: angular cordova-plugins ngcordova ionic2


    【解决方案1】:

    据我所知,您应该存储从subscribe 调用返回的subscription,然后调用unsubscribe()

    你会得到这样的东西:

    export class Pedometer {
       platform;
       watch;
       watchSub : Subscription;
       constructor () {
            this.platform = platform;
       }
       startWatching() {
           console.log('Starting to watch');
           this.watch = DeviceMotion.watchAcceleration(this.options);
           this.watchSub = this.watch.subscribe(result => {this.detectMotion(result)});
       }
       stopWatching() {
           console.log('Stop Watching');
           // this.watch.dispose();
           this.watchSub.unsubscribe();
           // this.watch.clearWatch();
       }
       detectMotion(result) {
           console.log('Current Readings: '+ JSON.stringify(result) );
           //.....do something with the results.....
           this.stopWatching(); // Stop and wait for a second before restarting
           setTimeout(this.startWatching(), 1000);
       }
    }
    

    【讨论】:

    • 谢谢@PierreDuc - 我在关注this ioinic1 版本。了解 watch 是订阅和取消订阅的句柄。再次感谢它确实帮助了我
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-14
    • 2019-11-12
    • 1970-01-01
    • 2019-11-15
    • 2022-01-20
    • 2020-06-23
    • 2018-03-27
    相关资源
    最近更新 更多