如何使用angular 2+创建和下载具有动态内容的文本/Json文件 [英] How to create and download text/Json File with dynamic content using angular 2+

查看:99
本文介绍了如何使用angular 2+创建和下载具有动态内容的文本/Json文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里我想知道如何创建文本文件或json文件并下载要填充的动态数据.

here i want to know how can i create a text file or json file and download it with dynamic data which is going to be filled with.

以下是我的

服务代码

  validateUserData(userId) {
    var headers = new Headers();

    return this.http.get(`${this.baseUrl}/Users?userId=`+userId,{headers: headers}).map(result => {

      return result.json();

    });
  }

component.ts

this.service.validateUserData(userId).subscribe( res => {

       console.log(res);    
       new Angular2Txt(res, 'My Report');
     });

在这里我想将响应发送到我必须创建的textFile或json文件中,以便用户能够下载我该怎么做 角度包

here i want to send the Response to a textFile or json file which i have to create it so that user can able to download how can i do it Angular package

我尝试了上述软件包,但是我只能下载空文件

i tried the above package but i able to download only empty file

推荐答案

它不必使用任何软件包,请尝试

it does not have to use any package,try this

https://stackblitz.com/edit/httpsstackoverflowcomquestions51806464如何创建和下载Downloa?file = src/app/app.component.ts

@Component({
  ...
})
export class AppComponent {
  private setting = {
    element: {
      dynamicDownload: null as HTMLElement
    }
  }


  fakeValidateUserData() {
    return of({
      userDate1: 1,
      userData2: 2
    });
  }

  //

  
  dynamicDownloadTxt() {
    this.fakeValidateUserData().subscribe((res) => {
      this.dyanmicDownloadByHtmlTag({
        fileName: 'My Report',
        text: JSON.stringify(res)
      });
    });

  }

  dynamicDownloadJson() {
    this.fakeValidateUserData().subscribe((res) => {
      this.dyanmicDownloadByHtmlTag({
        fileName: 'My Report.json',
        text: JSON.stringify(res)
      });
    });
  }
  
  

  private dyanmicDownloadByHtmlTag(arg: {
    fileName: string,
    text: string
  }) {
    if (!this.setting.element.dynamicDownload) {
      this.setting.element.dynamicDownload = document.createElement('a');
    }
    const element = this.setting.element.dynamicDownload;
    const fileType = arg.fileName.indexOf('.json') > -1 ? 'text/json' : 'text/plain';
    element.setAttribute('href', `data:${fileType};charset=utf-8,${encodeURIComponent(arg.text)}`);
    element.setAttribute('download', arg.fileName);

    var event = new MouseEvent("click");
    element.dispatchEvent(event);
  }
}

<a (click)="dynamicDownloadTxt()" >download Txt</a>
<a (click)="dynamicDownloadJson()" >download JSON</a>

这篇关于如何使用angular 2+创建和下载具有动态内容的文本/Json文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆