javascript - Ionic 2内部函数和外部函数

标签 javascript function angular typescript ionic2

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

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

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

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

关于javascript - Ionic 2内部函数和外部函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44776532/

相关文章:

c - 如何计算冒泡排序中的交换次数?

python - Python 中的多元微分

Angular 7 Router 不断将我重定向到 404 未找到页面

javascript - Model.reject() 导致 extjs 表单中的无效字段

javascript - 方法中的 TypeScript 调用方法 = TypeError : this. print is not a function

c# - 接口(interface)函数 C#

angular - 移动和网络的单一代码库

angular - Angular 中的依赖注入(inject)如何有用,因为它显然没有解决任何问题?

javascript - 带有 ajax 调用的 setTimeout

javascript - 如何使用 d3.force 对散点图进行动态、非重叠标记