如何在Typescript中的回调中访问类变量?

时间:2016-04-19 21:22:13

标签: javascript typescript

这是我目前的代码:

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不可用。我试过保存这个(自我=这个),但仍然没有运气。任何人都可以帮助我理解我所缺少的东西吗?

更新: 设置

var self = this;

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

2 个答案:

答案 0 :(得分:4)

  

this.devices不可用

一个常见问题。将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

答案 1 :(得分:0)

这是我的代码,它通过按钮点击事件为html textarea添加字符。

HTML

<div class="console-display">
<textarea [(ngModel)]="textAreaContent" name="mainText"></textarea>
    <div class="console-keys">
        <button (click)="getKeyInput($event)" name="key01" type="button" value="1">1</button>
        <button (click)="getKeyInput($event)" name="key02" type="button" value="2">2</button>
    </div>
</div>

TS

export class HomeComponent {
  tempString = "64";
  getKeyInput(event){
    let self = this;
    manageTextArea(self, event.target.value, this.textAreaContent);
  }
}

function manageTextArea(self , ch : string, textArea : string): void {
  if (checkCharacter_Number(ch)){
    self.textAreaContent += ch;
  }
  console.log(self.tempString);
}

工作正常。