Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将JS文件导入到Ionic/Angular 2中_Javascript_Angular_Typescript_Import_Module - Fatal编程技术网

Javascript 将JS文件导入到Ionic/Angular 2中

Javascript 将JS文件导入到Ionic/Angular 2中,javascript,angular,typescript,import,module,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 {

我正在尝试将一个非常简单的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安装j-i-c——保存

在typescript文件中,我要使用它:

import*作为jic从“j-i-c”导入

在我的app.component.ts中:

声明var jic:any

当我运行它并尝试记录全局变量
jic
时,它只是一个空对象
{}
。我假设这是因为我需要一个打字定义,我需要这方面的帮助——但我也想知道
JIC.js
是否需要重写。我试着导出两个函数
compress
upload
,然后像这样去掉
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工具
-但有一个问题-图像文件没有类型属性(它是null而不是
image/jpeg
,这使得它无法压缩。

根据github中的这个问题

您不能按原样导入它

您必须在缩小版中进行非常简单的修改,以便能够“要求”它作为一个模块:

j-i-c/dist/JIC.min.js

您可以更改
var jic=

通过
module.exports=

导入组件文件后,可以编写

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


并使用
jib.compress()
只要你们想

。这里有一个专门关于如何正确导入第三方JS的问题。谢谢,但打字的例子只是告诉你们如何使用npm安装打字软件包…我需要创建我自己的打字文件。你们可以继续使用那个种不需要打字的文件,来定义打字。它非常繁琐,你们需要k现在,整个库都正确地@ewizardI使用了ionic 3(基于angular 2构建),我认为这样的脚本是没有位置的,
“scripts”:[“./node\u modules/jssha/src/sha.js”]
…我没有看到
angular cli.json
我建议您跳过它添加到.json文件中脚本数组的步骤,只在组件中声明一个var并使用该函数。这可能会起作用。感谢我使用了ionic native
camera
选项来压缩图像。如果需要,我会给它一个快照休息时,我有完全相同的问题。唯一的问题是,当你使用相机压缩时,你不能确定最终的大小,因为这取决于相机的分辨率。目前,我正在尝试定制
压缩
功能并循环,直到我有了好的大小…我可能会在这里发布