How to use custom methods of the Cordova plugin in Angular / Ionic service

I am working on integrating a custom Cordova plugin into an Ionic app. We had a third-party creation of the Cordova plugin for interacting with a Bluetooth device. The launch cordova platform lsshows that the plugin is installed correctly:

$ cordova plugin ls
> com.sitename.product 0.0.0 "DeviceProbe"

The plugin contains a file probe.jscontaining methods for connecting, reading, polling, and other actions.

/plugins/com.sitename.product/www/probe.js

var callNative = function(service, action, success, error, args) {
    if(args === undefined) args = [];
    cordova.exec(success, error, service, action, args);
};

var thermProbe = {

    // Methods here

};

module.exports = thermProbe;

To use the plugin in our controllers, I need to create an Angular wrapper as described here .

I created a factory to handle this.

/lib/probe/probe.js

(function() {

    'use strict';

    var serviceId = 'Probe';
    angular.module('thermProbe').factory(serviceId, ['$q', Probe]);

    function Probe($q) {

        var service = {
            'connect': connect,
            'disconnect': disconnect,
            'getReading': getReading,
            'getName': getName, 
            'getHigh': getHigh,
            'getLow': getLow,
            'pollReading': pollReading,
            'stopPolling': stopPolling,
            'isPolling': isPolling
        };

        return service;

        // Method wrappers

        function connect() {

            var q = $q.defer(); 

            if($window.cordova){
              cordova.plugins.thermProbe.connect(function (result) {
                q.resolve(result);
              }, function (err) {
                q.reject(err);
              });
            }
            return q.promise;

        }

    }

})();

Probe . ( ionic run android), :

TypeError: Cannot read property 'connect' of undefined

, cordova.plugins.thermProbe.connect().

cordova.plugins.probe.connect(), .

/plugins/com.sitename.product/www/probe.js /lib/probe/probe.js?

+4
1

( console.log ing) .

$window probe, . , probe Cordova.

plugin.xml

<js-module src="www/probe.js" name="probe">
  <clobbers target="probe" />
</js-module>
<platform name="ios">
  <config-file target="config.xml" parent="/*">
    <feature name="probe">
      <param name="ios-package" value="productName"/>
    </feature>
  </config-file>
  ...
  ...
</platform>
<platform name="android">
  <config-file target="res/xml/config.xml" parent="/*">
    <feature name="probe">
      <param name="android-package" value="com.sitename.productName"/>
      <param name="onload" value="true" />
    </feature>
  </config-file>
  ...
  ...
</platform>

:

function connect() {

  var q = $q.defer(); 

  if($window.probe){
    $window.probe.connect(function (result) {
      q.resolve(result);
    }, function (err) {
      q.reject(err);
    });
  }

  return q.promise;

}
+1

All Articles