这是我当前的代码:

import {Page} from 'ionic-angular';
import {BLE} from 'ionic-native';

@Page({
  templateUrl: 'build/pages/list/list.html'
})
export class ListPage {
  devices: Array<{name:string, id: string}>;

  constructor() {
    this.devices=[];
  }
  startScan (){
    this.devices = []; // This "this" exists and works fine
    BLE.scan([],5).subscribe(
      (device)=>{
        if(device.name){
          this.devices.push({name:device.name,id:device.id});  // this.devices does not exists
        }
      },
      (err) => {
        console.log(JSON.stringify(err));
      }
      );
  }

  connectToDevice(device){
    BLE.connect(device.id).subscribe(success=>{
       console.log(JSON.stringify(success));
    });
  }
}

调用startScan函数时,我试图将返回的设备推入阵列,但是this.devices不可用。我曾尝试保存此(self = this),但仍然没有运气。谁能帮助我了解我所缺少的吗?

更新:
设置
var self = this;

在startScan()的顶部,然后在.subscribe回调中使用它便是答案!

最佳答案



常见问题。将startScan更改为箭头函数:

startScan = () => {
    this.devices = [];
    BLE.scan([],5).subscribe(
      (device)=>{
        if(device.name){
          this.devices.push({name:device.name,id:device.id});  // this.devices does not exists
        }
      },
      (err) => {
        console.log(JSON.stringify(err));
      }
      );
  }

更多

https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html

08-03 22:09