我已经创建了cordova插件并且已经在Ionic 1中使用过,它的工作原理。然后我尝试在Ionic 2中使用它,但我真的不知道如何调用该插件。我按照here的步骤创建自己的插件。这就是我所做的:
的plugin.xml
custombundle
myPlugin.js
<name>myPlugin</name>
<js-module src="www/myPlugin.js" name="myPlugin">
<clobbers target="myPlugin" />
</js-module>
你好-ionic.ts
module.exports = {
myFunction: function (success, failure) {
cordova.exec(success, failure, "myPlugin", "myFunction", []);
}
};
但很遗憾,它在import { Component } from '@angular/core';
declare var cordova: any;
@Component({
selector: 'page-hello-ionic',
templateUrl: 'hello-ionic.html'
})
export class HelloIonicPage {
constructor() {
}
click() {
if (typeof cordova !== 'undefined') {
cordova.plugins.myPlugin.myFunction();
}
}
}
中向我回复了错误 "Undefined myFunction"
。
答案 0 :(得分:4)
这就是我所做的。
<强>你好-ionic.ts 强>
import { Component } from '@angular/core';
declare var myPlugin: any;
@Component({
selector: 'page-hello-ionic',
templateUrl: 'hello-ionic.html'
})
export class HelloIonicPage {
constructor() {
}
click() {
myPlugin.myFuntion(
(data) => {
console.log(data);
},
(err) => {
console.log(err);
});
}
}
我来自declare var myPlugin: any;
的 myPlugin
,<clobbers target="myPlugin" />
名称。
注意:只需在设备中运行项目。
答案 1 :(得分:2)
以下教程是学习如何创建自定义cordova插件的好资源:
https://taco.visualstudio.com/en-us/docs/createplugintutorial/
我已经按照本教程创建了多个自定义插件,这些插件在Ionic2中运行良好。
还有一点要指出的是,教程没有提到:
您必须使用以下命令在离子2项目中添加您的自定义插件:
离子插件添加“自定义插件的文件夹路径”
更新:
在plugin.xml文件中,您已在target
代码中将“myPlugin”设置为clobbers
。
所以你应该按照以下方式调用你的函数
window.myPlugin.myFunction();
提示:每当您使用由您(或其他人)创建的自定义插件时,请使用Chrome开发者工具检查应用程序。在开发人员工具的控制台选项卡中,您可以检查window
和其他可用对象,并找出调用插件方法的正确方法。