ionic2 - 设备运动返回可观察但取消订阅给出错误

ionic2 - Device Motion returning observable but unsubscribe gives error

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

的片段
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 我了解到它 returns 一个 Observable

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

~达瓦尔

据我所知,您应该存储从 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);
   }
}