typescript 如何使用 angular 2+ 创建和下载带有动态内容的文本/Json 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51806464/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:34:38  来源:igfitidea点击:

How to create and download text/Json File with dynamic content using angular 2+

angulartypescript

提问by 2 Developer

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.

在这里,我想知道如何创建文本文件或 json 文件并使用将要填充的动态数据下载它。

below is my

下面是我的

service code

服务代码

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

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

      return result.json();

    });
  }

component.ts

组件.ts

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

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

here i want to send the Responseto 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

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

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

我试过上面的包,但我只能下载空文件

回答by Chunbin Li

it does not have to use any package,try this

它不必使用任何包,试试这个

https://stackblitz.com/edit/httpsstackoverflowcomquestions51806464how-to-create-and-downloa?file=src/app/app.component.ts

https://stackblitz.com/edit/httpsstackoverflowcomquestions51806464how-to-create-and-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>

回答by user184994

Firstly, there is a library we can use to handle saving the file. I've just tested it with FileSaverwhich seems to work, so that seems a good place to start.

首先,我们可以使用一个库来处理保存文件。我刚刚用FileSaver对其进行了测试,它似乎可以工作,因此这似乎是一个不错的起点。

Secondly, configure your HTTP request to return a Blob. Using HttpClient, we can simply do:

其次,配置您的 HTTP 请求以返回 Blob。使用HttpClient,我们可以简单地做:

let url = "https://jsonplaceholder.typicode.com/todos/1";
this.http.get(url, {responseType: 'blob'})

Finally, in the subscribe, save the blob. Using the npmpackage I mentioned earlier, this would be done like so:

最后,在订阅中,保存 blob。使用npm我之前提到的包,这将像这样完成:

import { saveAs } from 'file-saver/FileSaver';

// ...

    let url = "https://jsonplaceholder.typicode.com/todos/1";
    this.http.get(url, {responseType: 'blob'})
      .subscribe((res) => {
        console.log(res)
        saveAs(res, "myfile.json")
      })

The second option is the filename.

第二个选项是文件名。

Here is StackBlitz demo

这是 StackBlitz 演示

Just uncomment the saveAsline if you want to see it download the file.

saveAs如果您想看到它下载文件,只需取消注释该行。