Jane Dawson Jane Dawson - 9 months ago 50
Javascript Question

Return value from callback function in service to component

I'm using the Cordova WifiWizard Plugin in my Ionic 2 mobile app. Everything works fine, when I run it in the *.ts file of my page. In this case my code looks like:

Declaring WifiWizard before @Component:

declare var WifiWizard:any;

Call of WifiWizard and success / error methods:

setCurrentWifiAsHomeWifi() {
WifiWizard.getCurrentSSID(this.ssidSuccess, this.ssidError);

ssidSuccess = (ssid) => {
this.userService.setHomeWifi(this.user.$key, ssid);

ssidError = (err) => {
console.log("WiFi Wizard Error"+err);

However, I don't want to put all this wifi-logic in the page-component, but move it to a wifi provider / service instead. But I don't get this service to return the ssid-string to the component.


I tried many different things and I carefully read the post, linked by gyre (thank you for that). However, I still can't figure out a solution for my problem, and I think it's slightly different to the linked question.

Let me sketch the structure of my problem to make it more obviously to you:
structure of my serviceCall

I'm calling the wifiService from homePage.ts, e.g. using a promise:

setCurrentWifiAsHomeWifi() {
this.wifiService.loadWifiData().then( result=> {
console.log("returned SSID: "+result);

In wifiService.ts I need to implement "loadWifiData" which calls the wifiWizard plugin like this:

WifiWizard.getCurrentSSID(this.getWifiSuccess, this.getWifiError);

If this is successful, it passes the SSID-string to the "getWifiSuccess" method, if it fails it passes the error to "getWifiError". However the plugin call doesn't return any value to my homePage.

How can I return the outcome (SSID or error) to my homePage? I'm stuck here. Appreciate your help! Hope it became clearer now.

Answer Source

I solved it by letting loadWifiData() return a Promise and defining the code for the success- and reject-function directly in this Promise.

 loadWifiData() {
    return new Promise( (resolve, reject) => {
        // if successful:
        (ssid => {
          resolve (ssid);
        // if error:
        (error => { 
          reject (error);