javascript - 从普通的javascript调用角度组件函数
问题描述
我正在为我的网络应用程序使用 Angular,并且我的一个页面上需要蓝牙。我正在使用 loginov-rocks/bluetooth-terminal(https://github.com/loginov-rocks/bluetooth-terminal)进行蓝牙连接,它可以连接我的设备并从中查看数据。现在我遇到的问题是我无法从我的接收函数获取数据到我的角度组件,我可以将数据打印到控制台,但这不是我想要的,我想解析我的数据并在我的角度组件中设置一些变量它。这是我的代码:
let bluetooth = new BluetoothTerminal();
bluetooth.receive = function (data) {
console.log(data);
//i want to call ParseBtData here from my angular component to parse data
//or somehow send data and cach it for parsing inside my component
};
export class GpsAppComponent extends AppComponentBase implements OnInit
{
//all the angular stuff
parseBtData(data) {
//parse my BT data and set some variables inside my component...
};
}
我尝试在组件内部制作 BluetoothTerminal,但我仍然无法调用任何函数来解析我的数据。甚至有可能做到这一点,还是有其他方法可以解决我的问题?
解决方案
一般来说,如果您创建一个对象 javascript,您可以使用声明来做到这一点,那么唯一的就是覆盖“接收到的”数据。但是由于事件不受 Angular 控制,因此您需要对 Angular 说“某些东西”在 Angular 之外发生了变化,因此您需要使用 ngZone,例如:
//DISCLAMER: I don't know if work
declare var bluetooth = new BluetoothTerminal();
export class AppComponent implements AfterViewInit
{
constructor(private ngZone:NgZone,private dataService:DataService){}
ngAfterViewInit(){
bluetooth.receive = (data)=> {
this.ngZone.run(()=>{
this.dataService.sendData(data)
})
};
}
}
然后你只需要在你的服务中定义
bluethoodData:Subject<any>=new Subject<any>()
sendData(data:any)
{
this.bluethoodData.next(data)
}
您可以在任何组件中订阅 dataService.bluethoodData
this.dataService.bluethoodData.subscribe(res=>{
console.log(res)
})
推荐阅读
- java - getPrimaryClip() 正在返回空对象引用
- javascript - javascript 发布成功后隐藏/显示导航项
- python - Spacy Span Group
- flutter - Cocoapods 中的 Flutter pod 和 Flutter SDK 一样吗?
- haskell - 幻影类型“a”是刚性类型变量
- batch-file - 修改 .bat 文件以不仅启动同时进程,还关闭它们
- javascript - 对象作为反应子无效,但我使用的是反应文档官方代码
- python - 在python中按索引和值分组数据帧
- git - 自动在最后 n 次提交中引入更改
- node.js - 打字机。为什么 createQueryBuilder leftJoinAndSelect 有条件和无条件但在哪里有不同的结果?