[英]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.