管理来自 BluetoothSerial ionic 2 的 return 的承诺

Manage a return's promise from BluethoothSerial ionic 2

我正在编写一个代码来检查蓝牙连接是否启用。所以我这样做了:

$ ionic plugin add cordova-plugin-bluetooth-serial
$ npm install --save @ionic-native/bluetooth-serial

在我的构造中我有这个:

construnct(....
  private bluetoothSerial: BluetoothSerial,
  .....){..

现在这里

construnct(....
  private bluetoothSerial: BluetoothSerial,
  .....){..
this.bluetoothSerial.isEnabled(/*here*/);
 ...}

我需要管理蓝牙是否启用?

我创建了一个布尔变量,我想将其赋值为 true 或 false,这取决于蓝牙是否启用。但是要怎么做呢?

参考:

bluetoothSerial.isEnabled(
    function() {
        console.log("Bluetooth is enabled");
        //myboolflag=true; dosen't work!!!
    },
    function() {
        console.log("Bluetooth is *not* enabled");
    }
);

here

你应该像这样使用箭头函数:

bluetoothSerial.isEnabled(
    () => {
        console.log("Bluetooth is enabled");
        this.myboolflag = true; // Should work now!!!
    },
    () => {
        console.log("Bluetooth is *not* enabled");
    }
);

通过使用箭头函数,this 属性 不会被覆盖并且仍然引用组件实例。