javascript - 从离子项目中的打字稿调用javascript函数
问题描述
我在我的 ionic 项目中添加了一个插件,所以我有这样的 java 代码和 JS 代码:
cordova.define("cordova-sms-plugin.Sms", function(require, exports, module) {
'use strict';
var exec = require('cordova/exec');
var sms = {};
function convertPhoneToArray(phone) {
if (typeof phone === 'string' && phone.indexOf(',') !== -1) {
phone = phone.split(',');
}
if (Object.prototype.toString.call(phone) !== '[object Array]') {
phone = [phone];
}
return phone;
}
sms.send = function(phone, message, filename, options, success, failure) {
// parsing phone numbers
phone = convertPhoneToArray(phone);
// parsing options
var replaceLineBreaks = false;
var androidIntent = '';
if (typeof options === 'string') { // ensuring backward compatibility
window.console.warn('[DEPRECATED] Passing a string as a third argument is deprecated. Please refer to the documentation to pass the right parameter: https://github.com/cordova-sms/cordova-sms-plugin.');
androidIntent = options;
}
else if (typeof options === 'object') {
replaceLineBreaks = options.replaceLineBreaks || false;
if (options.android && typeof options.android === 'object') {
androidIntent = options.android.intent;
}
}
// fire
exec(
success,
failure,
'Sms',
'send', [phone, message, filename, androidIntent, replaceLineBreaks]
);
};
sms.hasPermission = function(success, failure) {
// fire
exec(
success,
failure,
'Sms',
'has_permission', []
);
};
module.exports = sms;
});
我想sms.send(...)
在我的 Typescript 代码中调用该函数。我试图像这样导入文件:
import sms from '../../../plugins/cordova-sms-plugin/www/sms.js';
或者
import * as Sms from '../../../plugins/cordova-sms-plugin/www/sms.js';
或者
window['window']['sms']['send'](...)
但没有任何作用,离子找不到send()
功能,你能帮帮我吗?
解决方案
您没有以正确的方式调用。在您的ts
文件中不需要导入js
文件。
您可以使用全局范围变量直接调用,也可以.d.ts
为此插件接口创建定义文件并导入您的.ts
文件。确保您的插件安装正确后,按照以下步骤cordova-sms-plugin
从TS
文件调用
步骤1。你可以参考JS variable
使用windows object
所以在.ts
文件中声明它
declare var window: any;
第2步。现在你可以这样称呼它window.sms.send
let phone: string;
//Set the value of phone
let message: string;
//Set the value of message
let options = {
"replaceLineBreaks: false"
//
};
//Call the function
window.sms.send(phone,message,options,(result: any) => {
console.log("SuccessFully Done...");
}, (err: any) => {
console.log("An error has occuered :" + err.code);
})
我还在 GitHub 上为你找到了一个示例项目。你可以参考这个来查看代码:
推荐阅读
- amazon-athena - AWS Glue 爬虫需要从许多具有相同架构的文件中创建一个表
- c++ - MacOS 上的 QProcess 尝试使用 diskutil
- django - 如何使用 Django 标签为多个 url 设置导航栏链接“活动”
- c# - 如何允许字符串中某个位置的字符
- python - 如何修复 pysftp 间歇性“[Errno 2] 没有这样的文件”?
- visual-studio-code - 如何防止 VS Code 折叠尾随空行?
- python - 如何强制 SHIFT+ENTER 运行选择并立即在 vscode 中运行 ipython 执行它?
- r - 使用 checkboxInput 将 ggplot2 更改为 plotly
- java - 如何检查实现接口的参数类型?
- r - 使用 ggplot2 将文本添加到 forestplot 时出现错误