Reputation: 133
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;
})
}
}
Upvotes: 0
Views: 783
Reputation: 12414
You are using the this.test
inside a function declaration: setTimeout(function () {
so you just need to change that to an arrow function: setTimeout(() => {
like this:
readDataFromSerial() {
BluetoothSerial.write("g").then((response)=> {
setTimeout(() => { // <-- the change goes here
alert("write");
BluetoothSerial.read().then((response)=> {
alert(this.test);
alert(response);
})
}, 1000)
})
}
Upvotes: 1
Reputation: 37343
use arrow =>
function in the setTimeout
function :
setTimeout(()=> {
alert("write");
BluetoothSerial.read().then((response)=> {
alert(this.test);
alert(response);
})
}, 1000)
Upvotes: 4