Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 531
Tomas Avatar asked Apr 19 '16 21:04

Tomas


2 Answers

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.gitbooks.io/typescript/content/docs/arrow-functions.html

like image 124
basarat Avatar answered Sep 28 '22 08:09

basarat


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.

like image 32
Katax Emperore Avatar answered Sep 28 '22 08:09

Katax Emperore