2017-06-27 7 views
0

Ich entwickle gerade eine Anwendung mit Ionic 2 mit der Bibliothek BLE https://github.com/evothings/cordova-ble. Was ich hier wissen will, ich habe eine Funktion connectToDevice, die die Funktion ble.connectToDevice aufruft, die die Funktion onConnected aufruft. Innerhalb der Funktion onConnected möchte ich die Funktion enableNotification (deviceNotification (deviceNotification)) aufrufen, die außerhalb der Funktion connectToDevice liegt. Aber ich bekomme den Fehler: TypeError: _this.enableCoinNotification ist keine Funktion.Ionic 2 interne Funktion und externe Funktion

Könnte jemand dieses Problem lösen und es mir erklären?

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

Wie rufen Sie 'connectToDevice' an? – Nirus

+0

kann ich es im Konstruktor aufrufen, habe ich den Code bearbeitet – Junior

+0

hat die Lösung Ihnen geholfen? – Nirus

Antwort

2

hinzufügen bind API:

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

this verloren geht, wenn Sie nur die Funktionsdefinition durch Pfeil Funktion definiert passieren.


Alternativ:

Ja, ich stimme mit @Junior

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

Durch die Rückrufe wechselnden Funktionen Pfeil Sie auf das übergeordnete Objekt this Umfang verweisen können.

+0

Hallo, danke für deine Antwort, deine Lösung ist gut. Es gibt auch alle meine Funktion mit dem Fettpfeil zu deklarieren => das wird helfen, dies als Klassenschluss zu haben – Junior

Verwandte Themen