2017-06-27 7 views
0

私は現在、ライブラリBLE https://github.com/evothings/cordova-bleを使用してIonic 2でアプリケーションを開発中です。ここで知りたいのは、関数onConnectedを呼び出す関数ble.connectToDeviceを呼び出すconnectToDevice関数です。関数onConnectedの中で、関数connectToDeviceの外部にある関数enableNotification(device)を呼び出したいと思います。しかし、私はエラーが発生します:TypeError:_this.enableCoinNotificationは関数ではありません。イオン2の内部機能と外部機能

誰かがこの問題を解決し、それを私に説明できますか?

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) 
    } 
} 
+0

どのように 'connectToDevice'を呼びますか? – Nirus

+0

私はコンストラクタでそれを呼び出すことができます。コード – Junior

+0

を編集しました。 – Nirus

答えて

2

bind API追加:

let startNotifications = (device) => { 
    console.log("Start Notification called"); 
    this.enableCoinNotification(device); 
    }; 
    startNotifications.bind(this); // <-- Add this line 

thisをあなたは矢印機能によって定義された唯一の関数定義を通過する際に失われます。

また

はい、私はあなたが親thisオブジェクトスコープに参照できる機能を矢印のコールバックを変更することにより@Junior

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

に同意します。

+0

こんにちは、あなたの答えは、あなたの解決策は良いです。私のすべての関数を太い矢印で宣言することもできます。>これは、これをクラスクロージャーとして持つのに役立ちます – Junior

関連する問題