javascript - How to access class variable in callback in Typescript? -


here current code:

import {page} 'ionic-angular'; import {ble} '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" exists , works fine     ble.scan([],5).subscribe(       (device)=>{                 if(device.name){           this.devices.push({name:device.name,id:device.id});  // this.devices 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 trying push returned device array, however, this.devices not available. have tried saving (self=this), still no luck. can me understand missing?

update: setting

var self = this; 

at top of startscan() , using in .subscribe callback answer!

this.devices not available

a common issue. change startscan arrow function:

startscan = () => {     this.devices = [];     ble.scan([],5).subscribe(       (device)=>{                 if(device.name){           this.devices.push({name:device.name,id:device.id});  // this.devices not exists         }                    },       (err) => {         console.log(json.stringify(err));       }       );   } 

more

https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html


Comments

Popular posts from this blog

java - nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet Hibernate+SpringMVC -

sql - Postgresql tables exists, but getting "relation does not exist" when querying -

asp.net mvc - breakpoint on javascript in CSHTML? -