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!
startScan? It is possible that you have it bound to the wrong (or no) object. Try addingconsole.log(this)at the top ofstartScanand see if it logs the object you are expecting.self = thisat the top ofstartScan()didn't work for you. There's no logical reason it shouldn't work hehe. If you do that, and thenconsole.log(self)inside of the subscribe callback, what do you get? ----- Secondly, have you tried making a variable that references, notthis, butthis.devicesspecifically? Maybe likevar _devices = this.devices;after the declaration in startScan. Then_devices.push(...in the subscribe. Let us know!let self = this;? That worked for me anyway.