Angular 2 从 getList() 下载 json csv 或 Excel 格式的响应数据

Angular 2 download json response data from getList() in csv or Excel format

最后的游戏很简单,我的 Angular 应用程序在名为 customers-list.component.html 的视图上获取并生成数据条目列表,如下所示:

Name:  Olivia
Age:  23
Active:  true

----------------
Name:  Julia
Age:  22
Active:  true

----------------
Name:  Wes
Age:  23
Active:  true

----------------
Name:  Gabe
Age:  24
Active:  false

我希望能够下载上述数据条目的 .csv 文件。

customers-list.component.ts 中,我试过这个函数 getcsvFile(),定义了通过 service.ts 传入的数据,定义了一个新的 Blob() 函数和使用 JSON.stringify(data) 并传入 getCustomersList() 数据并将其保存为 .csv:

export class CustomersListComponent implements OnInit {

  customers: Observable<Customer[]>;

  constructor(private customerService: CustomerService) { }
...... 
 getcsvFile() {

      this.customers = this.customerService.getCustomersList();
      let file = new Blob([JSON.stringify(this.customers)], { type: 'data:application/csv;charset=utf-8,content_encoded_as_url' });
      saveAs(file, 'customerList.csv')
    }

}

继承人service.ts:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class CustomerService {

  private baseUrl = 'http://localhost:8000/customers';

  constructor(private http: HttpClient) { }
.........
  getCustomersList(): Observable<any> {
    return this.http.get(`${this.baseUrl}/`);
  }
}

但是当我下载 csv 文件并打开它时,我看不到输入的实际数据,而是所有这些仍然采用 json 格式的奇怪信息:

{
"_isScalar":false,
"source":{"_isScalar":false,
"source":{"_isScalar":false,
"source":{"_isScalar":true,
"value":{"url":"http://localhost:8000/customers/",
"body":null,"reportProgress":false,
"withCredentials":false,
"responseType":"json",
"method":"GET",
"headers":{"normalizedNames":{},
"lazyUpdate":null,"headers":{}},
"params":{"updates":null,
"cloneFrom":null,"encoder":{},
"map":null},
"urlWithParams":"http://localhost:8000/customers/"}},
"operator":{"concurrent":1}},
"operator":{}},
"operator":{}
}

当我想看到更接近这个的东西时:

[
{"id": 2, "name": "Olivia", "age": 23, "active": true}, 
{"id": 3, "name": "Julia", "age": 22, "active": true}, 
{"id": 4, "name": "Wes", "age": 23, "active": true}, 
{"id": 5, "name": "Gabe", "age": 24, "active": false}
]

我错过了什么?

看看你的 saveAs 函数的作用会很有趣,但无论如何,如果你不想安装模块,你可以自己轻松安装。

  // Download CSV
download(data: any, filename: string, columns: string, header: string, delimiter: string | undefined) {
  const csvData = this.convertToCSV(data, columns, header, delimiter);
  const link: any = document.createElement('a');
  link.setAttribute('style', 'display:none;');
  document.body.appendChild(link);
  const blob = new Blob([csvData], {type: 'text/csv'});
  link.href = window.URL.createObjectURL(blob);

  const isIE = !!(<any> document).documentMode;

  if (isIE) {
    navigator.msSaveBlob(blob, filename + '.csv');
  } else {
    link.download = filename + '.csv';
  }
  link.click();
  link.remove();
}

并将您的 JSON 转换为 CSV,您可以这样做:

/**
 * exports json (array) data to CSV
 * @param data
 * @param {string} columns
 * @param {string} header
 * @param {string | undefined} delimiter
 * @returns {string}
  */
  convertToCSV(data: any, columns: string, header: string, delimiter: string | 
undefined) {
  let row = '';
  const del = delimiter ? delimiter : ';';
  const head = header.split(del);
  const col = columns.split(del);

  // creating the header
  for (const headerTxt of head) {
    row += headerTxt + del;
  }
  row += '\r\n';
  //  start with the rows
  for (const dataset of data) {
    let line = '';
    for (let i = 0; i < col.length; i++) {
      let dataToAdd = dataset[col[i]];
      if (dataset[col[i]] == null || dataset[col[i]] === undefined) {
        dataToAdd = '';
      }
      line += '"' + dataToAdd + '"' + del;
    }
    row += line + '\r\n';
  }
  return row;
}

所以在你的情况下你很可能会这样称呼它:

download(this.customers, 'customer', 
'id,name,age,active', 
'ID,Name,Age,Active', ',') 

希望对您有所帮助:)

编辑:

我明白了,您没有订阅您的可观察对象,这很可能是错误。试试这个:

 getcsvFile() {

    this.customerService.getCustomersList()
     .pipe(take(1)) // <-- HERE 
     .subscribe(customers=>{ // <-- AND HERE
      if (customers) {
        download(customers, 'customer','id,name,age,active','ID,Name,Age,Active', ',');
      }
   });

}

问候