Ionic2实战-Cordova插件安装

前言

WebApp的开发想和系统底层硬件打交道怎么能少了Cordova插件的支持呢?本节我们讲一下 Ionic2里面Cordova插件的使用。

Ionic2的Cordova插件分为两种,1、官方包装过的,2、第三方的。
使用方式有很大的不同。

官方Cordova插件使用方式

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);
}

第三方Cordova插件使用方式

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

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

ionic plugin add cordova-plugin-networkinterface;

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

.....

  

......

可以看到该插件的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);
      });
    }
  }
}

你可能感兴趣的:(Ionic2实战-Cordova插件安装)