onner onner -4 years ago 115
TypeScript Question

How to access class variables in this situation?

I'm using bluetooh serial from ionic native.I want to access a variable defined in class when i'm read somenthing from serial.
I set the value for variable but when i want to display it from inside of read function shows me undefined(at alert(this.test)).What can i do ?
Here is my code:

import { Component } from '@angular/core';

import {NavController, Platform} from 'ionic-angular';
import {BluetoothSerial} from "ionic-native/dist/es5/index";

@Component({
selector: 'functions',
templateUrl: 'functions.html'
})
export class Functions {
public data:any;
monStart:Boolean;
devices:any;
connected:Boolean;
onConnect:Boolean;
public test:any;


constructor(public navCtrl: NavController,platform:Platform) {
this.test="aaaa";
platform.ready().then(() => {

});
}

readDataFromSerial() {
BluetoothSerial.write("g").then((response)=> {
setTimeout(function () {
alert("write");
BluetoothSerial.read().then((response)=> {
alert(this.test);
alert(response);
})
}, 1000)
})
}

showListOfDevices() {
BluetoothSerial.list().then((response)=>{
alert("Devices:"+JSON.stringify(response));
this.devices=response;
})
}


}

Answer Source

use arrow => function in the setTimeout function :

setTimeout(()=> {
          alert("write");
          BluetoothSerial.read().then((response)=> {
             alert(this.test);   
             alert(response);
          })
    }, 1000)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download