【问题标题】:IONIC BLE (Bluetooth Low Energy) - device list not showing upIONIC BLE(蓝牙低功耗) - 设备列表未显示
【发布时间】:2017-06-17 09:53:01
【问题描述】:

当我扫描 BLE 设备时,会找到它们,但是,在找到它们之后,我会尝试将这些设备添加到列表中。

问题:应用程序上未显示列表(或为空)。

JS:

import { Component } from '@angular/core';
import { BLE } from '@ionic-native/ble';

@Component({
  selector: 'page-about',
  templateUrl: 'about.html'
})
export class AboutPage {

  device_list: any[];

  constructor(public alertCtrl: AlertController, public ble: BLE) {

  }

  scan(){
    this.device_list = [];

    this.ble.scan([], 5).subscribe(device => {

      // ADDING TO LIST
      this.device_list.push(device);

    }, error => {
      console.log('Check your bluetooth connection.');
    });

  }

}

如果我使用console.log(JSON.stringify(device)) 而不是this.device_list.push(device),则设备将被打印出来,但我需要将它们添加到列表中并在应用程序上显示该列表。

为什么会这样?

HTML:

<ion-header>
  <ion-navbar>
    <ion-title>
      About
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <button ion-button (click)="scan()" color="danger" block>SCAN</button>

  <ion-list>
    <ion-item *ngFor="let item of device_list">
        {{item.id+"----"item.name}}
    </ion-item>
  </ion-list>
</ion-content>

【问题讨论】:

  • 好的,很明显,列表很好,里面有设备。但是,列表仅在以下情况下显示(更新):我切换到另一个选项卡并返回此选项卡(包含列表)或我切换到另一个应用程序并返回此应用程序如何解决此问题?

标签: javascript angular ionic-framework bluetooth bluetooth-lowenergy


【解决方案1】:

尝试这种方式添加到列表中:

this.device_list = device.slice();

基本上, slice() 操作会克隆数组并返回对新数组的引用。我在想,因为您只是将数据推送到device_list,所以对列表的引用保持不变(尽管实际内容发生了变化),因此角度不会重新渲染视图。

【讨论】:

  • 我尝试过:this.device_list = device.slice(); 然后this.device_list.push(device); 但错误仍然相同..
【解决方案2】:

已解决

不得不添加 NgZone(不确定它的作用)。

import { Component, NgZone } from '@angular/core';
import { BLE } from '@ionic-native/ble';

@Component({
  selector: 'page-about',
  templateUrl: 'about.html'
})
export class AboutPage {

  device_list: any[];

  constructor(private zone:NgZone, public ble: BLE) {

  }

  scan(){
    this.device_list = [];

    this.ble.scan([], 5).subscribe(device => {
      // ADD TO LIST
      this.zone.run(() => {
       this.device_list.push(device);
      });
    }, error => {
      this.app_alert('Check your bluetooth connection.');
    });

  }

}

【讨论】:

  • 是什么让您找到了这个解决方案?
  • 在某个论坛找到。基本上,*ngFor 的值没有更新,这会以某种方式更新它们。
猜你喜欢
  • 2021-04-09
  • 2015-05-05
  • 2016-06-14
  • 2021-10-27
  • 1970-01-01
  • 1970-01-01
  • 2021-04-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多