2017-03-22 8 views
0

私はイオンnativeからシリアルを使用しています。私はシリアルから読んだときにクラスで定義された変数にアクセスしたいと思います。 変数の値を設定しましたが、読み込み関数の中から表示したいときは、私は定義されていません(警告(this.test))。私は何ができますか?ここで が私のコードです:この状況でクラス変数にアクセスする方法は?

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; 
     }) 
     } 


    } 

答えて

4

使用setTimeout機能で=>機能を矢印:

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

ありがとうございました!それは働いています:) – onner

+0

ようこそ、それを解決策としてマークすることを忘れないでください;) –

1

あなたは、関数宣言内this.testを使用している:setTimeout(function() {ので、あなただけの矢印にそれを変更する必要があります関数:setTimeout(() => {

このように:

readDataFromSerial() { 
    BluetoothSerial.write("g").then((response)=> { 
     setTimeout(() => { // <-- the change goes here 
      alert("write"); 
      BluetoothSerial.read().then((response)=> { 
       alert(this.test); 
       alert(response); 
      }) 
     }, 1000) 
    }) 
} 
+0

私は "Bougarfaouiエルhoucine"と同じことを見て、 – Diullei

関連する問題