离子2内部功能和外部功能



我目前使用库ble ble https://github.com/evothings/cordova-ble开发了使用Ionic 2的应用程序。我想在这里知道的是,我有一个函数connectTodeVice,该功能称为函数ble.connectTodeVice,该函数调用函数连接。在函数上连接的内部,我想调用函数ConnectTodeVice外部的函数enableNotification(设备(。但是我得到错误: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)
   }
}

添加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));

通过将回调更改为箭头函数,您可以参考parent this对象范围。

相关内容

  • 没有找到相关文章

最新更新