首页 > 解决方案 > 从普通的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,但我仍然无法调用任何函数来解析我的数据。甚至有可能做到这一点,还是有其他方法可以解决我的问题?

标签: javascriptangularweb-componentweb-bluetooth

解决方案


一般来说,如果您创建一个对象 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)
   })

推荐阅读