angular2-download

import { Injectable } from '@angular/core';

function invorkLoadProxy(ifr, cache, callBackFn, resolve){
let fn = function(){
if (ifr.$$eventFn){
ifr.removeEventListener('load', ifr.$$eventFn);
}
let r = cache || [];
r.forEach((r)=>{
document.body.removeChild(r);
})
callBackFn();
resolve(true);
}
ifr.$$eventFn = fn;
ifr.addEventListener('load', fn);
}

/**
* 下载服务
* @auther xiufu.wang
*/
@Injectable()
export class MbDownloadService {

constructor() {}

post(url: string, params?: {[name: string]: Array<string | number>| string | number}){
return new Promise((resolve, reject)=>{
let cache = [];
params = params || {};
let ifr = this.createHtmlDocumentAndAppendBody('iframe', {name: 'ng2downloadIframe', src: 'about:blank'}, cache);
ifr.style.display = 'none';
invorkLoadProxy(ifr, cache, ()=>{this.onDownLoad();}, resolve);

let formCtrl:any = this.createHtmlDocumentAndAppendBody('form', {target: 'ng2downloadIframe', action: url, method: 'POST'}, false);

for (var key in params){
if (params[key] !== undefined && params.hasOwnProperty(key)){
let v = params[key];
if (Array.isArray(v)){
v = v.join(',');
}
formCtrl.appendChild(this.createHtmlDocument('input', {type: 'hidden', name: key, value: v}, false));
}
}

formCtrl.submit();
document.body.removeChild(formCtrl);
});
}

get(url: string, params?: {[name: string]: Array<string | number>| string | number}){
return new Promise((resolve, reject)=>{
let cache = [];
params = params || {};
let ifr = this.createHtmlDocumentAndAppendBody('iframe', {name: 'ng2downloadIframe', src: 'about:blank'}, cache);
ifr.style.display = 'none';
invorkLoadProxy(ifr, cache, ()=>{this.onDownLoad();}, resolve);

let urlParams = '_doc='+ new Date().getTime();
for (let key in params){
if (params.hasOwnProperty(key) && params[key]){
let v = params[key];
if (Array.isArray(v)){
v = v.join(',');
}
urlParams = urlParams + '&' + key + '=' + v;
}
}

let p = url.indexOf('?') > 0 ? ('&' + urlParams) : ('?' + urlParams)
ifr.setAttribute('src', url + p);
});
}

private onDownLoad(){}

private createHtmlDocument(tagName, context, cache){
context = context || {};
let el = document.createElement(tagName);
for (let key in context){
if (context.hasOwnProperty(key) && context[key]){
el.setAttribute(key, context[key]);
}
}
if (cache){
cache.push(el);
}
return el;
}

private createHtmlDocumentAndAppendBody(tagName, context, cache){
let el = this.createHtmlDocument(tagName, context, cache);
document.body.appendChild(el);
return el;
}

private bindEventListener(el, type, func){
el.removeEventListener(type, func);
el.addEventListener(type, func);
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值