Angular中如何通过点击按钮取消device orientation的订阅
问题原因
你这里的核心错误是复用了同一个类属性this.orientation同时存储RxJS订阅对象和罗盘返回的角度数值,订阅第一次触发回调时,this.orientation就会被toFixed(2)返回的字符串覆盖,字符串本身没有unsubscribe方法,自然取消订阅失效。
修正代码
TS 部分
首先新增独立的订阅存储属性,避免变量覆盖,同时补充重复订阅防护、空值判断逻辑:
import { Subscription } from 'rxjs'; // ... 类内部代码 // 专门存储罗盘数值 orientation: string = ''; // 专门存储订阅实例 private orientationSub: Subscription | null = null; // 监听设备朝向变化 async watchOrientation() { // 重复点击启动时先销毁之前的订阅,避免内存泄漏 if (this.orientationSub) { this.orientationSub.unsubscribe(); } const options = { frequency: 500, }; this.orientationSub = this.deviceOrientation.watchHeading(options).subscribe( (data: DeviceOrientationCompassHeading) => { // 数值写入专门的存储属性,不覆盖订阅实例 this.orientation = data.magneticHeading.toFixed(2) }, (error: any) => console.log(error) ); console.log('watchOrientation button clicked') }; // 停止监听设备朝向变化 async stopOrientation() { // 空值判断,避免无订阅时调用方法报错 if (this.orientationSub) { this.orientationSub.unsubscribe(); this.orientationSub = null; } console.log('stopOrientation button clicked'); };
HTML 部分
你的HTML绑定逻辑本身没有问题,无需修改,如果需要展示当前罗盘数值可以额外加标签绑定{{ orientation }}即可。
额外注意事项
如果是在App启动初期调用监听方法,建议包裹在this.platform.ready()回调中执行,避免插件未初始化导致调用失败。
内容的提问来源于stack exchange,提问作者vlntn
相关产品推荐
相关产品推荐

