Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/30.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 2以csv或Excel格式从getList()下载json响应数据_Json_Angular_Csv_Get_Response - Fatal编程技术网

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

Angular 2以csv或Excel格式从getList()下载json响应数据,json,angular,csv,get,response,Json,Angular,Csv,Get,Response,游戏的结局很简单,我的Angular应用程序在一个名为customers-list.component.html的视图中获取并生成一个数据条目列表,如下所示: 我希望能够下载上述数据项的.csv文件 在customers-list.component.ts中,我尝试了这个函数getcsvFile,定义了通过service.ts传入的数据,定义了一个新的Blob函数,使用了JSON.stringifydata并传入getCustomersList数据并将其保存为.csv: 当我想看到更接近这一点的

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

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

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

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

[
{"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();
}
希望这有助于:

编辑:

我明白了,你没有订阅你的可观测数据,那很可能是错误。试试这个:

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

}

问候语

使用ngx papaparse saveAs从文件保护程序模块导入*作为“文件保护程序”的saveAs;还有,我应该把这些方法放在哪里?因为当我试图从getcsvFile方法调用它时,它一直在说undefined,它也从convertToCsv方法中发出了这个错误:CustomerListComponent.html:13错误类型错误:无法读取位于的undefined的属性“split”customerListComponent.push../src/app/customers list/customers-list.ts.customerListComponent.convertToCSV customers list.component.ts:62 Atlaso发出此错误类型错误:header.split不是customerListComponent.push../src/app/cust的函数,当我像这样调用它时{this.customers=this.customerService.getCustomersList;let file=new Blob[JSON.stringifythis.customers],{type:'data:application/csv;charset=utf-8,content\u encoded\u as\u url'};this.convertToCSVfile,'customer',['id','name','age','active active'],'id','name','age','active downloadfile,'customer',谢谢,但是我仍然收到这个错误类型错误:header.split不是第62行的函数------------------->const head=header.splitdel;是的,那是对的,它不可能工作,相应地更新了它
{
"_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}
]
  // 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();
}
/**
 * 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', ',');
      }
   });

}