【问题标题】:calling angular component function from plain javascript从普通的javascript调用角度组件函数
【发布时间】:2021-08-27 13:26:50
【问题描述】:

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

【问题讨论】:

  • 只是分享解决方法的想法,创建一些全局对象或变量并为其分配值。
  • 您应该尝试绑定您的上下文(将this 绑定到您的蓝牙接收函数),这样您应该能够调用组件类中的函数。并将您的 bluetooth.receive 放在您的类中,例如在其构造函数中。这里有一些这样做的例子:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • 问题是你在angular的更新周期之外使用了一个函数,基本上angular不知道任何不在其生态系统内的东西,你必须创建一个服务并且必须从你的组件中调用该服务.

标签: javascript angular web-component web-bluetooth


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2020-02-25
      • 1970-01-01
      • 1970-01-01
      • 2016-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-05
      • 2016-07-18
      相关资源
      最近更新 更多