分享

Ionic2使用第三方cordova插件(非Ionic2官方支持的native cordova插件)

 飞鹰飞龙飞天 2017-06-04

注:找了一个晚上,这篇文章的解决方案才是最靠谱的,已验证

Ionic2官方提供了丰富的native cordova插件,比如:Camera、Device等等,使用方式也很简单:

1、添加插件支持:ionic plugin add cordova-plugin-device;

2、在页面ts文件中声明: import { Device } from 'ionic-native';

3、在相关方法中调用:

getDeviceInfo(){

  console.log('Device UUID is: ' + Device.uuid);

}

Ionic2native组件虽然丰富,但是实际开发过程中,我们总是会遇到使用非官方支持cordova组件的情况,比如:微信支付、支付宝等。

以一个获取本机IP地址的cordova插件为例,简单讲解一下非官方支持的cordova插件的用法:

1、添加插件:ionic plugin add cordova-plugin-networkinterface;

2、打开插件配置文件的my-iconic2-project\plugins\cordova-plugin-networkinterface\config.xml:

.....

<js-module src="www/networkinterface.js" name="networkinterface">
  <clobbers target="window.networkinterface" />
</js-module>

......

可以看到该插件的target为window.networkinterface,所以,在app运行期该插件对象应该声明并绑定在window对象上。那么,我们使用此类插件的方式应该为:

index.ts:

import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';

declare var networkinterface: any;

 

@Component({
selector: 'page-index',
templateUrl: 'index.html'
})
export class IndexPage {

constructor(public navCtrl: NavController, public navParams: NavParams) {}

  ionViewDidLoad() {
    console.log('ionViewDidLoad IndexPage');
  }

  getIPAddress(){

    if('undefined' != typeof networkinterface){
      networkinterface.getIPAddress(function(ip){
        alert(ip);
      });

    }

  }

}

 

不过我还看到stackoverflow有一种实现方式:

declare var cordova: any;

....

 

getIPAddress(){

  if('undefined' != typeof cordova){

    cordova.plugins.networkinterface.getIPAddress(function(ip){

      alert(ip);

    });

  }

}

我认为这种方式,使用config.xml为如下形式的cordova插件:

.....

<js-module src="www/networkinterface.js" name="networkinterface">
  <clobbers target="cordova.plugins.networkinterface" />
</js-module>

......

不过由于时间原因,我并没有去验证。

 

另外: 测试要在模拟器或者手机环境。

 

 

 

 

 

 

 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多