如何在ionic 3代码中解决此ngFor问题

时间:2018-10-25 14:34:23

标签: angular ionic-framework

我有一个Cordova蓝牙插件,该插件工作正常,但是当我尝试显示已配对设备的列表时,我无法在html页面上显示它们,而只是处于警报状态。我已经尽力了,但是我无法在应用程序的html页面上显示数据。当我在真实设备上运行应用程序时,我无法通过控制台真正收到该错误。我是离子和棱角新手,我将不胜感激任何帮助。谢谢

home.html

<ion-header>
  <ion-navbar>
    <ion-title>
      BlueTooth Printer
    </ion-title>
  </ion-navbar>
</ion-header>
<ion-content>
 
  <ion-list>
      <ion-item *ngFor=" let device of devicelists">
        {{device?.address}}
      </ion-item>
  </ion-list>

</ion-content>

这是我的 home.ts 代码

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

 declare var bluetoothSerial: any;

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

  devicelists: any;

  constructor(public navCtrl: NavController) {
   
  }

  ionViewDidLoad(){
   this.isEnabled();
   this.listDevices();
  }

  listDevices(){
    bluetoothSerial.list(
      function(devices) {
      devices.forEach(function(device) {
        alert(device.address); // This is working just fine
        this.devicelists = device; // But this is what is not working
      })
  }, 
  function(failure){
    alert(failure);
  });
  }
  isEnabled(){
    bluetoothSerial.enable(
      function() {
          alert("Bluetooth is enabled");
      },
      function() {
          alert("The user did *not* enable Bluetooth");
      }
  );
  }

  connect(){
    bluetoothSerial.connect(
     function(data){
      console.log("Success");
      alert(data)
    });
  }
  desconnect(){
    bluetoothSerial.disconnect(function(data){
      console.log("Success");
      alert(data)
    },function(err){
      console.log("Error");
      alert(err)
    })
  }
  printText(){
    bluetoothSerial.write(function(data){
      console.log("Success");
      alert(data)
  },function(err){
      console.log("Error");
      alert(err)
  }, "String to Print")
  }

}

2 个答案:

答案 0 :(得分:1)

通过使用数组函数语法而不是常规函数语法来更改listDevices()方法的实现

listDevices() {
  bluetoothSerial.list(devices => this.devicelists = devices)
}

这样,您将可以绑定到正确的this

答案 1 :(得分:0)

尝试将回调更改为类似箭头的功能

listDevices(){
bluetoothSerial.list(
  function(devices) {
  devices.forEach(function(device) {
    alert(device.address); // This is working just fine
    this.devicelists = device; // But this is what is not working
  })
}

  listDevices(){
    bluetoothSerial.list(
      (devices) => {
      devices.forEach((device) => {
        alert(device.address); // This is working just fine
        this.devicelists = device;
      })
  })
}