Tomas
Tomas

Reputation: 621

How to access class variable in callback in Typescript?

Here is my current code:

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

When calling startScan function I am trying to push returned device to array, however, this.devices is not available. I have tried saving this (self=this), but still with no luck. Can anyone help me to understand what i am missing?

UPDATE: Setting

var self = this;

at the top of startScan() and then using it in .subscribe callback is the answer!

Upvotes: 7

Views: 8793

Answers (2)

basarat
basarat

Reputation: 275799

this.devices is not available

A common issue. Change startScan to an arrow function:

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

More

https://basarat.gitbook.io/typescript/future-javascript/arrow-functions

Upvotes: 13

Katax Emperore
Katax Emperore

Reputation: 465

Here is my code, it add characters to html textarea with button click event.

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

It works fine.

Upvotes: 2

Related Questions