在这种情况下如何访问类变量?

时间:2017-03-22 19:10:21

标签: angular typescript

我正在使用来自离子native的bluetooh序列。我想在读取序列中的somenthing时访问类中定义的变量。 我为变量设置了值,但是当我想从read函数内部显示它时,我显示未定义(在 alert(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;
        })
      }


    }

2 个答案:

答案 0 :(得分:4)

=>函数中使用箭头setTimeout函数:

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

答案 1 :(得分:1)

您正在使用函数声明中的this.testsetTimeout(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)
    })
}