注:找了一个晚上,这篇文章的解决方案才是最靠谱的,已验证
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="workinterface" />
</js-module>
......
可以看到该插件的target为workinterface,所以,在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){
workinterface.getIPAddress(function(ip){
alert(ip);
});
}
}
我认为这种方式,使用config.xml为如下形式的cordova插件:
.....
<js-module src="www/networkinterface.js" name="networkinterface">
<clobbers target="workinterface" />
</js-module>
......
不过由于时间原因,我并没有去验证。
另外: 测试要在模拟器或者手机环境。