首页 > 解决方案 > 从离子项目中的打字稿调用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()功能,你能帮帮我吗?

标签: javascriptjavatypescriptcordovaionic-framework

解决方案


您没有以正确的方式调用。在您的ts文件中不需要导入js文件。

您可以使用全局范围变量直接调用,也可以.d.ts为此插件接口创建定义文件并导入您的.ts文件。确保您的插件安装正确后,按照以下步骤cordova-sms-pluginTS文件调用

步骤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 上为你找到了一个示例项目。你可以参考这个来查看代码:

https://github.com/abritopach/ionic-receiver-sms


推荐阅读