How to read csv file in Angular-4 assets

2020-06-06 01:58发布

问题:

I am new to angular-4 and I want to read a csv file from angular-4 assets directory, file size 5mb and I dont't want to read this file from django back-end server because this file is to show only demo graphs and I don't need to send 5mb extra request to server, thanks currently I follow this stack overflow question

Files Reading

private fs = require('fs');

readCsvData () {
    let allText = this.fs.readFileSync('assets/demo-Results.csv', 'utf8');
    console.log(allText)
    // this.extractData(allText);
}

Error is :

ShowDemoResultsComponent.html:17 ERROR TypeError: this.fs.readFileSync is not a function at ShowDemoResultsComponent.webpackJsonp.../../../../../src/app/show-demo-results/show-demo-results.component.ts.ShowDemoResultsComponent.readCsvData (show-demo-results.component.ts:119) at Object.eval [as handleEvent] (ShowDemoResultsComponent.html:17) at handleEvent (core.es5.js:12023) at callWithDebugContext (core.es5.js:13493) at Object.debugHandleEvent [as handleEvent] (core.es5.js:13081) at dispatchEvent (core.es5.js:8615) at core.es5.js:9226 at HTMLButtonElement. (platform-browser.es5.js:2651) at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:425) at Object.onInvokeTask (core.es5.js:3881)

回答1:

In case you use the new HttpClient class (@angular/common/http), then you will have to set the responseType to 'text', otherwise the HttpClient class would try to interpret the content as json and raise a SyntaxError...

e.g.:
this.http.get('assets/file.csv', {responseType: 'text'})
    .subscribe(
        data => {
            console.log(data);
        },
        error => {
            console.log(error);
        }
    );


回答2:

I finally find a answer Here is how I done it:

csvUrl = 'assets/demo-Results.csv';
readCsvData () {
      this.http.get(this.csvUrl)
        .subscribe(
          data => {
            console.log(data.text())
          },
          err => {
            console.log(err)
          });
  }