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

How to access class variable in callback in Typescript?

本文关键字:回调 访问 类变量 Typescript      更新时间:2023-09-26

这是我当前的代码:

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回调中使用它就是答案!

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.gitbook.io/typescript/future-javascript/arrow-functions

这是我的代码,它通过按钮点击事件将字符添加到html文本区域。

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);
}

它运行良好。