【问题标题】:How to create and download text/Json File with dynamic content using angular 2+如何使用 Angular 2+ 创建和下载具有动态内容的文本/Json 文件
【发布时间】:2018-08-12 06:54:26
【问题描述】:

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

下面是我的

服务代码

  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');
     });

在这里我想将 Response 发送到我必须创建它的 textFile 或 json 文件,以便用户能够下载我该怎么做 Angular package

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

【问题讨论】:

  • 顺便说一下GET请求不需要发送content-type标头
  • 是的,我知道编辑过它以及解决该问题的任何方法?
  • 您使用的是哪个版本的 Angular?还有,你用的是Http还是HttpClient?
  • 使用 Angular 6,但仅使用 http,因为它已从 Angular 4 升级到 Angular 6
  • 您可能会发现使用HttpClient 会更容易,因为很容易将其配置为返回Blob。

标签: angular typescript


【解决方案1】:

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

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>

【讨论】:

  • 这种方法我以前遵循的问题是我在锚标签中创建按钮 点击服务必须的锚标签后被调用并且必须下载数据
  • 我更新了;您可以在服务获取数据后致电dynamicDownload。
  • 我的意思是你已经在元素右边创建了锚标签,你在模板中使用了按钮元素,在我的应用程序中我使用 标签作为按钮而不是按钮,所以这可以适用你也可以用锚按钮更新按钮标签
  • 我将按钮更改为锚点,但我认为这与您要使用的 HtmlElement 没有任何关系。在调用 ValidateUserDate 方法 之后,您只需在我的示例中调用 dynamicDownloadJson 方法
  • 当 JSON 很大时,使用 Chrome 下载时出现网络错误。
【解决方案2】:

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

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

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

最后,在订阅中,保存 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")
      })

第二个选项是文件名。

Here is StackBlitz demo

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

【讨论】:

    【解决方案3】:

    你可以这样做:

    let res = "Text to save in a text file";
    const blob = new Blob([res], { type: 'text/csv' });
    const url = window.URL.createObjectURL(blob);
    window.open(url);
    

    【讨论】:

    • Incase json,它会打开一个新选项卡。知道如何下载 json 吗?
    • @HardikPatel 我不知道。对我来说,在 Chrome 中,它会非常短暂地打开一个新标签,然后标签消失,文件会自动下载。是否取决于您的浏览器设置?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-19
    • 1970-01-01
    • 2022-01-20
    • 2018-12-25
    • 2020-09-13
    • 1970-01-01
    • 2020-09-17
    相关资源
    最近更新 更多