最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin6浏览0评论

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!

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!

Share Improve this question edited Apr 21, 2016 at 6:46 Tomas asked Apr 19, 2016 at 21:22 TomasTomas 6211 gold badge6 silver badges14 bronze badges 5
  • 2 Where are you calling startScan? It is possible that you have it bound to the wrong (or no) object. Try adding console.log(this) at the top of startScan and see if it logs the object you are expecting. – Alex McMillan Commented Apr 19, 2016 at 21:24
  • startScan is called from view (html) on button click. this.devices does exists before I call BLE.scan, however, in a subscribe callback "this" bees "subscribe" context – Tomas Commented Apr 20, 2016 at 7:04
  • I have absolutely no idea how trying self = this at the top of startScan() didn't work for you. There's no logical reason it shouldn't work hehe. If you do that, and then console.log(self) inside of the subscribe callback, what do you get? ----- Secondly, have you tried making a variable that references, notthis, but this.devices specifically? Maybe like var _devices = this.devices; after the declaration in startScan. Then _devices.push(... in the subscribe. Let us know! – aaronofleonard Commented Apr 20, 2016 at 15:08
  • 2 I must be going mad.... Tried putting var self = this; and it worked this time.... I am sure I have tried this before as this would be something I would do writing javascript. So, yeah, it works :) it does not update view though when pushing, but i am sure its angular related. Thanks! – Tomas Commented Apr 21, 2016 at 6:44
  • Brilliant! Though, as it's Typescript, shouldn't it be let self = this;? That worked for me anyway. – jon_two Commented Feb 13, 2017 at 17:00
Add a ment  | 

2 Answers 2

Reset to default 13

this.devices is not available

A mon 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.gitbook.io/typescript/future-javascript/arrow-functions

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.

发布评论

评论列表(0)

  1. 暂无评论