javascript - 将 JS 文件导入 Ionic/Angular 2

标签 javascript angular typescript import module

我正在尝试将一个非常简单的 JS 库导入 Angular 2。这是该库的样子:

JIC.js

var jic = {
        /**
         * Receives an Image Object (can be JPG OR PNG) and returns a new Image Object compressed
         * @param {Image} source_img_obj The source Image Object
         * @param {Integer} quality The output quality of Image Object
         * @param {String} output format. Possible values are jpg and png
         * @return {Image} result_image_obj The compressed Image Object
         */

        compress: function(source_img_obj, quality, output_format){

             var mime_type = "image/jpeg";
             if(typeof output_format !== "undefined" && output_format=="png"){
                mime_type = "image/png";
             }


             var cvs = document.createElement('canvas');
             cvs.width = source_img_obj.naturalWidth;
             cvs.height = source_img_obj.naturalHeight;
             var ctx = cvs.getContext("2d").drawImage(source_img_obj, 0, 0);
             var newImageData = cvs.toDataURL(mime_type, quality/100);
             var result_image_obj = new Image();
             result_image_obj.src = newImageData;
             return result_image_obj;
        },

        /**
         * Receives an Image Object and upload it to the server via ajax
         * @param {Image} compressed_img_obj The Compressed Image Object
         * @param {String} The server side url to send the POST request
         * @param {String} file_input_name The name of the input that the server will receive with the file
         * @param {String} filename The name of the file that will be sent to the server
         * @param {function} successCallback The callback to trigger when the upload is succesful.
         * @param {function} (OPTIONAL) errorCallback The callback to trigger when the upload failed.
         * @param {function} (OPTIONAL) duringCallback The callback called to be notified about the image's upload progress.
         * @param {Object} (OPTIONAL) customHeaders An object representing key-value  properties to inject to the request header.
         */

        upload: function(compressed_img_obj, upload_url, file_input_name, filename, successCallback, errorCallback, duringCallback, customHeaders){

            //ADD sendAsBinary compatibilty to older browsers
            if (XMLHttpRequest.prototype.sendAsBinary === undefined) {
                XMLHttpRequest.prototype.sendAsBinary = function(string) {
                    var bytes = Array.prototype.map.call(string, function(c) {
                        return c.charCodeAt(0) & 0xff;
                    });
                    this.send(new Uint8Array(bytes).buffer);
                };
            }

            var type = "image/jpeg";
            if(filename.substr(-4).toLowerCase()==".png"){
                type = "image/png";
            }

            var data = compressed_img_obj.src;
            data = data.replace('data:' + type + ';base64,', '');

            var xhr = new XMLHttpRequest();
            xhr.open('POST', upload_url, true);
            var boundary = 'someboundary';

            xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);

        // Set custom request headers if customHeaders parameter is provided
        if (customHeaders && typeof customHeaders === "object") {
            for (var headerKey in customHeaders){
                xhr.setRequestHeader(headerKey, customHeaders[headerKey]);
            }
        }

        // If a duringCallback function is set as a parameter, call that to notify about the upload progress
        if (duringCallback && duringCallback instanceof Function) {
            xhr.upload.onprogress = function (evt) {
                if (evt.lengthComputable) {  
                    duringCallback ((evt.loaded / evt.total)*100);  
                }
            };
        }

            xhr.sendAsBinary(['--' + boundary, 'Content-Disposition: form-data; name="' + file_input_name + '"; filename="' + filename + '"', 'Content-Type: ' + type, '', atob(data), '--' + boundary + '--'].join('\r\n'));

            xhr.onreadystatechange = function() {
            if (this.readyState == 4){
                if (this.status == 200) {
                    successCallback(this.responseText);
                }else if (this.status >= 400) {
                    if (errorCallback &&  errorCallback instanceof Function) {
                        errorCallback(this.responseText);
                    }
                }
            }
            };


        }
};

到目前为止我已经试过了:

npm install j-i-c --save

在 typescript 文件中我想使用它:

从 'j-i-c' 导入 * 作为 jic;

在我的 app.component.ts 中:

声明 var jic: any;

当我运行它并尝试记录全局变量 jic 时,它只是一个空对象 {}。我假设这是因为我需要一个类型定义,我需要这方面的帮助 - 但我也想知道 JIC.js 是否需要重写。我尝试导出 compressupload 这两个函数并去掉 jic 对象声明,如下所示:

        export function compress(source_img_obj, quality, output_format){

             var mime_type = "image/jpeg";
             if(typeof output_format !== "undefined" && output_format=="png"){
                mime_type = "image/png";
             }


             var cvs = document.createElement('canvas');
             cvs.width = source_img_obj.naturalWidth;
             cvs.height = source_img_obj.naturalHeight;
             var ctx = cvs.getContext("2d").drawImage(source_img_obj, 0, 0);
             var newImageData = cvs.toDataURL(mime_type, quality/100);
             var result_image_obj = new Image();
             result_image_obj.src = newImageData;
             return result_image_obj;
        };

        /**
         * Receives an Image Object and upload it to the server via ajax
         * @param {Image} compressed_img_obj The Compressed Image Object
         * @param {String} The server side url to send the POST request
         * @param {String} file_input_name The name of the input that the server will receive with the file
         * @param {String} filename The name of the file that will be sent to the server
         * @param {function} successCallback The callback to trigger when the upload is succesful.
         * @param {function} (OPTIONAL) errorCallback The callback to trigger when the upload failed.
         * @param {function} (OPTIONAL) duringCallback The callback called to be notified about the image's upload progress.
         * @param {Object} (OPTIONAL) customHeaders An object representing key-value  properties to inject to the request header.
         */

        export function upload(compressed_img_obj, upload_url, file_input_name, filename, successCallback, errorCallback, duringCallback, customHeaders){

            //ADD sendAsBinary compatibilty to older browsers
            if (XMLHttpRequest.prototype.sendAsBinary === undefined) {
                XMLHttpRequest.prototype.sendAsBinary = function(string) {
                    var bytes = Array.prototype.map.call(string, function(c) {
                        return c.charCodeAt(0) & 0xff;
                    });
                    this.send(new Uint8Array(bytes).buffer);
                };
            }

            var type = "image/jpeg";
            if(filename.substr(-4).toLowerCase()==".png"){
                type = "image/png";
            }

            var data = compressed_img_obj.src;
            data = data.replace('data:' + type + ';base64,', '');

            var xhr = new XMLHttpRequest();
            xhr.open('POST', upload_url, true);
            var boundary = 'someboundary';

            xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);

        // Set custom request headers if customHeaders parameter is provided
        if (customHeaders && typeof customHeaders === "object") {
            for (var headerKey in customHeaders){
                xhr.setRequestHeader(headerKey, customHeaders[headerKey]);
            }
        }

        // If a duringCallback function is set as a parameter, call that to notify about the upload progress
        if (duringCallback && duringCallback instanceof Function) {
            xhr.upload.onprogress = function (evt) {
                if (evt.lengthComputable) {  
                    duringCallback ((evt.loaded / evt.total)*100);  
                }
            };
        }

        xhr.sendAsBinary(['--' + boundary, 'Content-Disposition: form-data; name="' + file_input_name + '"; filename="' + filename + '"', 'Content-Type: ' + type, '', atob(data), '--' + boundary + '--'].join('\r\n'));

        xhr.onreadystatechange = function() {
            if (this.readyState == 4){
                if (this.status == 200) {
                    successCallback(this.responseText);
                }else if (this.status >= 400) {
                    if (errorCallback &&  errorCallback instanceof Function) {
                        errorCallback(this.responseText);
                    }
                }
            }
        };

那么,为什么记录到控制台的对象是空的?如何正确导入此库?另外,我正在尝试这样做,因为我找不到可用的 angular2/ionic 图像压缩包。我找到了 ng2-img-tools - 但有一个问题 - 图像文件没有类型属性(它是 null 而不是 image/jpeg 并且这使得它不可能压缩。

最佳答案

根据github中的这个issue
https://github.com/brunobar79/J-I-C/issues/47
您不能按原样导入它。

您必须在缩小版本中进行非常简单的修改才能将其作为模块“要求”:

j-i-c/dist/JIC.min.js中,
你可以改变
var jic =
通过
module.exports =

在你导入组件文件后,你可以写

从 'j-i-c/dist/JIC.min' 导入 * 作为 jicLib; 声明 const jib:any = jicLib;';

并在需要时使用 jib.compress()

关于javascript - 将 JS 文件导入 Ionic/Angular 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45258350/

相关文章:

javascript - 如何从字符串变量访问对象属性

javascript - 如何在 Angular JS 中使用自定义 json 数据格式创建下拉列表

angular - 组件中的变量仅在 Angular 4 服务中的第二次函数调用后才会更新

javascript - 如何过滤 select 元素的 ng-options 中的数据?

typescript - 类型 'HTMLCollectionOf<HTMLCanvasElement>' 必须有一个返回迭代器的 '[Symbol.iterator]()' 方法

javascript - 表单提交时的 Bootstrap 模态控制

javascript - 如何安全地加载 JavaScript 库

css - 如何从 html 中删除主机组件标签

typescript 检查类型 A === 类型 B | C型

typescript - 未捕获的类型错误 : Cannot read property 'release' of undefined