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

xa9qqrwz  于 2023-05-30  发布在  TypeScript
关注(0)|答案(2)|浏览(201)

以下是我的当前代码:

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函数时,我试图将返回的设备推送到阵列,但是,此.devices不可用。我试着保存这个(自我=这个),但仍然没有运气。谁能帮我了解我错过了什么?
更新:设置

var self = this;

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

3qpi33ja

3qpi33ja1#

此.设备不可用
一个共同的问题。将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

2ic8powd

2ic8powd2#

下面是我的代码,它添加字符到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);
}

它工作正常。

相关问题