Search code examples
cordovaangularpromisecordova-pluginsionic2

Cordova (Ionic2) custom plugin: manage Angular2 new Promise() with cordova.exec() successHandler


I am building a Cordova plugin to use with Ionic2. I am kind of experienced with Cordova (and custom plugins) but rather new to Ionic2 (and hence also new at Angular2, TypeScript).

(What I am asking now, I used to manage it with Jquery Deferred)

In my "app.component.ts" file I have:

import...

declare var MyPlugin: any;

@Component({
  templateUrl: 'app.html'
})

export class MyApp {
  ...
  initializeApp() {
    this.platform.ready().then(() => {
      StatusBar.styleDefault();
      MyPlugin.action();
    });
  }
  ...
}

I won't detail the "plugin.xml" file for my plugin. This works fine.

The "MyPlugin.js" goes like that:

var PLUGIN_NAME = "MyPlugin";

var MyPlugin =function(){};

MyPlugin.action(){
    cordova.exec(
        successResultHandler,
        errorResultHandler,
        PLUGIN_NAME,
        action,
        []
    );
} 
exports.module=MyPlugin;

In my Java Class linked to "MyPlugin.js" file I have something like:

public class MyPlugin extends CordovaPlugin {

    @Override
    public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException {
          //something async
          callbackContext.success()
    }
}

When the Java class triggers the callbackContext.success, the JS cordova.exec will launch the function successResultHandler. I was wondering how to use the Angular2 Promise to catch the async event???

I started to write some code but it doesn't make sense the order I should use.

I was thinking of doing something like that in "MyPlugin.js":

MyPlugin.action(){
   return new Promise(function(resolve,reject){
    cordova.exec(
        successResultHandler,
        errorResultHandler,
        PLUGIN_NAME,
        action,
        []
    );
    });
} 

But of course it doesn't make any sense, how do you catch the result of the function successResultHandler in resolve that way.

Has anyone an idea?


Solution

  • The resolve and reject parameters that the Promise constructor passes into the callback function are themselves functions, so you should be able to do something like this:

    MyPlugin.action(){
       return new Promise((resolve,reject) => {
            cordova.exec(
                resolve,
                reject,
                PLUGIN_NAME,
                action,
                []
            );
        });
    };
    

    Then invoke it like this:

    MyPlugin.action().then(() => {
        console.log("Success");
    },(err) => {
        console.error(err);
    });