【问题标题】:Angular 2 array template update not workingAngular 2 数组模板更新不起作用
【发布时间】:2018-09-15 21:35:00
【问题描述】:

我有一个使用 cordova BLE 插件的组件。当扫描开始查找设备时,它会将找到的每个设备推送到对象数组中。在我的模板中,我使用*ngFor 循环遍历对象,但模板没有更新并显示设备列表,即使我console.log(deviceList) 可以看到它已填充。该数组称为deviceList

蓝牙.ts

import { Component, Input, Output, EventEmitter } from '@angular/core';
import { Observable, Subscription } from 'rxjs/Rx';
import { BLE } from '@ionic-native/ble';


@Component({
selector: 'bluetooth',
templateUrl:'bluetooth.html'
})
export class Bluetooth {

/* new */
showWizard = true;
buttonConnected = false;
step = "BLEStepOne";
deviceList = [];

  constructor(public ble: BLE) {
}

ionViewDidLoad() {
  this.scanForDevices();
}

hideWizardCMD(){
    this.showWizard = false;
}

showWizardCMD(){
    this.showWizard = true;
}

gotoStep(step){
    this.step = step;
    if(step == "BLEStepTwo"){
        console.log('ble scan start');
        this.scanForDevices();
    }
}

scanForDevices(){
  console.log("scan for devices");
  this.deviceList = [];
  this.ble.startScan([]).subscribe(device => {
    this.deviceList.push(device);
    console.log(this.deviceList);
  });
}

}

蓝牙.html

<div class="not-logged-in" *ngIf="step=='BLEStepOne' && !buttonConnected">
<h2 class="smaller">Claim your Bel</h2> 
<p>Click to wake the button</p>
<img class="button-image" src="assets/images/button.png" />
<div class="buttons">
    <a class="btn btn-lg blank" (click)="hideWizardCMD()" href="#" >Skip</a> 
    <a class="btn btn-lg" (click)="gotoStep('BLEStepTwo')" href="#">Next</a> 
</div>
</div>

<div class="not-logged-in" *ngIf="step=='BLEStepTwo' && !buttonConnected">
<h2 class="smaller">Claim your Bel</h2> 
<p>Select your button to claim</p>
<ion-list>
  <ion-item *ngFor="let device of deviceList">
    <ion-label>{{device.id}}</ion-label>
    <ion-toggle [(ngModel)]="device.connected" (ngModelChange)="toggleConnection($event,device)"></ion-toggle>
  </ion-item>
</ion-list>
<div class="buttons">
    <a class="btn btn-lg" (click)="gotoStep('BLEStepOne')" href="#">Back</a> 
    <a class="btn btn-lg" (click)="gotoStep('BLEStepOne')" href="#">Claim</a> 
</div>
</div>

【问题讨论】:

  • 设备列表在订阅中更新,这是一个异步调用。所以代码看起来不错AFAIK。或许你可以尝试导入ChangeDetectionRef,通过调用detectChanges()方法手动触发变更检测。

标签: angular bluetooth-lowenergy angular2-template angular-arrays


【解决方案1】:

组件应用缺少实现 onChanges

【讨论】:

    【解决方案2】:

    我认为正确的方法是使用 NgZone。

    import { Component, NgZone } from '@angular/core';

    然后:

    constructor(public ble: BLE, private zone: NgZone) {
    }
    
    scanForDevices(){
      this.deviceList = [];
      this.ble.startScan([]).subscribe(device => {
        this.zone.run(() => {
          this.deviceList.push(device);
        });
      });
    }
    

    【讨论】:

      猜你喜欢
      • 2017-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-13
      • 1970-01-01
      • 1970-01-01
      • 2017-12-09
      • 1970-01-01
      相关资源
      最近更新 更多