【问题标题】:Ionic Bluetooth serial SubscribeRawData update UIIonic 蓝牙串口 SubscribeRawData 更新 UI
【发布时间】:2017-10-30 14:19:23
【问题描述】:

我正在使用这个插件https://github.com/don/BluetoothSerial 来管理蓝牙连接等,我在 arduino Leonardo 上使用 HC-06 模块。一切正常,问题出在移动应用程序上。 这是home.ts

connect() {
    this.blt = this.bluetoothSerial.connect("XX:XX:XX:XX:XX:XX");
    this.blt.subscribe((data) => {
        this._disable1 = false;
        this._connected = true;

        this.bluetoothSerial.subscribeRawData().subscribe((dt) => {
            this.bluetoothSerial.read().then((dd) => {
                this.onDataReceive(dd)
            });
        });
    }, (error) => {
        this._connected = false;
        this.setStatus("Not Connected");
    });
}

sendToHc(num) {
    this.bluetoothSerial.write(""+num).then((ok) => { });
}

dummyCheck() {
    // Do nothing
}

onDataReceive(dd) {
    this._debug += "\n" + JSON.stringify(dd);

}

在 home.html 上有一个按钮调用 connect() 和另一个调用 sendToHc 并带有参数。到目前为止一切正常。问题是当 subscribeRawData 从 arduino 读取响应时,它不会自动更新 UI。我必须插入第三个按钮来调用 dummyCheck() 并在更新 UI 之后。是否有在读取响应时自动更新 UI?

【问题讨论】:

    标签: angular bluetooth arduino ionic3


    【解决方案1】:

    我很确定嵌套订阅在 Angular 范围之外,并且当更新到达时,不会运行更改检测。当您按下虚拟按钮时,会触发 click 事件,该事件会触发更改检测,并且您的更新在 DOM 上变得可见。您可以使用 ChangeDetectorRef 手动运行更改检测:

    import { ChangeDetectorRef } from '@angular/core';
    constructor(private cdr: ChangeDetectorRef) {}
    
    this.bluetoothSerial.subscribeRawData().subscribe((dt) => {
      this.bluetoothSerial.read().then((dd) => {
        this.onDataReceive(dd);
        this.cdr.detectChanges(); // either here
       });
    });
    
    onDataReceive(dd) {
      this._debug += "\n" + JSON.stringify(dd);
      this.cdr.detectChanges(); // or here
    }
    

    可以在here 找到有关此的文档。而here 是一篇关于该主题的非常好的文章。

    【讨论】:

      【解决方案2】:

      我在同样的情况下苦苦挣扎,cdr 也解决了我的错误。正如 David 所提到的,问题在于 DOM 没有得到更新。这是我的代码,如果它对您或任何人有帮助。

      if(this.BLconnected == false) {
        this.shared.showLoading('Please wait. App is connecting to the Glove');
        this.connectToBT(); //Function to connect to the Bluetooth
      }else {
      //I set the delimiter as ';' because i print ';' at every print end in my arduino
        this.bluetoothSerial.subscribe(';').subscribe((data) => {
            this.spokenWord = data;
            this.cdr.detectChanges();
            console.log(data);
      });
      

      【讨论】:

        猜你喜欢
        • 2017-02-09
        • 1970-01-01
        • 2021-10-11
        • 2012-01-31
        • 1970-01-01
        • 1970-01-01
        • 2022-10-26
        • 1970-01-01
        • 2016-01-28
        相关资源
        最近更新 更多