繁体   English   中英

从普通 javascript 调用 angular 组件 function

[英]calling angular component function from plain javascript

我正在为我的 web 应用程序使用 angular,并且我的一个页面上需要蓝牙。 我正在使用 loginov-rocks/bluetooth-terminal( https://github.com/loginov-rocks/bluetooth-terminal )进行蓝牙连接,它可以连接我的设备并从中查看数据。 现在我遇到的问题是我无法从收到的 function 到我的 angular 组件中获取数据,我可以将数据打印到控制台,但这不是我想要的,我想解析我的数据并在我的 ZD121B8624A0FFC55B7 组件中设置一些变量 from68它。这是我的代码:

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

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

我设法通过在组件内移动我的蓝牙并执行以下操作来解决我的问题:

this.bluetooth.receive = (data) => {
        //console.log(data);
        this.writeToTerminalConsole(data);
    };

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM