离子2内部函数和外部函数

时间:2017-06-27 09:19:56

标签: javascript function angular typescript ionic2

我目前正在使用库BLE https://github.com/evothings/cordova-ble使用Ionic 2开发应用程序。我想知道的是,我有一个函数connectToDevice,它调用函数ble.connectToDevice来调用函数onConnected。在onConnected函数内部我想调用函数connectToDevice外部的函数enableNotification(device)。但我收到错误:TypeError:_this.enableCoinNotification不是函数。

有人可以解决这个问题并向我解释一下吗?

export class BleProvider {
 constructor(){
  this.connectToDevice(device)
 }

 connectToDevice(device){
   let onConnected = (device) => {
    console.log("Connected to device: " + device.name);
    return startNotifications(device);
  },
  onDisconnected = (device) => {
    console.log('Disconnected from device: ' + device.name);
  },
  onConnectError = (error) => {
    console.log('Connect error: ' + error);
  };

setTimeout(() => {
  ble.connectToDevice(
    device,
    onConnected,
    onDisconnected,
    onConnectError)
  }, 500);

  let startNotifications = (device) => {
    console.log("Start Notification called");
    this.enableCoinNotification(device) // ERROR : TypeError: _this.enableCoinNotification is not a function
  };
 }

  enableCoinNotification(device){

   let onNotificationSuccess = (data) =>{
    console.log('characteristic data: ' + ble.fromUtf8(data));
   },
   onNotificationError = (error) =>{
   };
  ble.enableNotification(
   device,
   this.coinEventNotificationUUID,
   onNotificationSuccess,
   onNotificationError)
   }
}

1 个答案:

答案 0 :(得分:2)

添加bind API:

  let startNotifications = (device) => {
    console.log("Start Notification called");
    this.enableCoinNotification(device);
  };
  startNotifications.bind(this); // <-- Add this line
只传递箭头功能定义的功能定义时,

this会丢失。

<强>可替换地:

是的,我同意 @Junior

ble.connectToDevice(device,
   (...arg) => onConnected(...arg),
   (...arg) => onDisconnected(...arg),
   (...arg) => onConnectError(...arg));

通过将回调更改为箭头函数,您可以引用父this对象范围。