UNPKG

yoyo-ng-modulewindy

Version:

服务于52ABP模板的前端开源的相关组件内容。整合了ng-alain和你NG ZORRO的内容

110 lines 4.1 kB
import { Injectable, Inject } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { saveAs } from 'file-saver'; import { LazyService } from 'yoyo-ng-module/util'; import { DA_ZIP_CONFIG } from './interface'; var ZipService = /** @class */ (function () { function ZipService(config, http, lazy) { this.config = config; this.http = http; this.lazy = lazy; } ZipService.prototype.init = function () { var config = Object.assign({ url: "//cdn.bootcss.com/jszip/3.1.5/jszip.min.js", utils: [], }, this.config); return this.lazy.load([config.url].concat(config.utils)); }; ZipService.prototype.check = function (zip) { if (!zip) throw new Error('get instance via `ZipService.create()`'); }; /** 解压 */ ZipService.prototype.read = function (fileOrUrl, options) { var _this = this; return new Promise(function (resolve, reject) { _this.init().then(function () { // from url if (typeof fileOrUrl === 'string') { _this.http .request('GET', fileOrUrl, { responseType: 'arraybuffer' }) .subscribe(function (res) { JSZip.loadAsync(res, options).then(function (ret) { return resolve(ret); }); }, function (err) { reject(err); }); return; } // from file var reader = new FileReader(); reader.onload = function (e) { JSZip.loadAsync(e.target.result, options).then(function (ret) { return resolve(ret); }); }; reader.readAsBinaryString(fileOrUrl); }); }); }; /** 创建 Zip 实例,用于创建压缩文件 */ ZipService.prototype.create = function () { var _this = this; return new Promise(function (resolve) { _this.init().then(function () { var zipFile = new JSZip(); resolve(zipFile); }); }); }; /** * 下载URL资源并写入 zip * @param zip Zip 实例 * @param path Zip 路径,例如: `text.txt`、`txt/hi.txt` * @param url URL 地址 */ ZipService.prototype.pushUrl = function (zip, path, url) { var _this = this; this.check(zip); return new Promise(function (resolve, reject) { _this.http.request('GET', url, { responseType: 'arraybuffer' }).subscribe(function (res) { zip.file(path, res); resolve(); }, function (error) { reject({ url: url, error: error }); }); }); }; /** * 保存Zip并执行打开保存对话框 * * @param zip zip 对象,务必通过 `create()` 构建 * @param options 额外参数, */ ZipService.prototype.save = function (zip, options) { this.check(zip); var opt = Object.assign({}, options); return new Promise(function (resolve, reject) { zip .generateAsync(Object.assign({ type: 'blob' }, opt.options), opt.update) .then(function (data) { if (opt.callback) opt.callback(data); saveAs(data, opt.filename || 'download.zip'); resolve(); }, function (err) { reject(err); }); }); }; ZipService.decorators = [ { type: Injectable }, ]; /** @nocollapse */ ZipService.ctorParameters = function () { return [ { type: undefined, decorators: [{ type: Inject, args: [DA_ZIP_CONFIG,] }] }, { type: HttpClient }, { type: LazyService } ]; }; return ZipService; }()); export { ZipService }; //# sourceMappingURL=zip.service.js.map