J.Doe
J.Doe

Reputation: 606

Display CSV Data with Angular

I am Trying to display the content of a CSV File in Angular.

To Test if it can read the .csv it I wrote following Method:

public readCsv(){
    this.httpClient.get('/testdata/csv/test.csv', {responseType: 'text'})
    .subscribe(
        data => {
            console.log(data);
        },
        error => {
            console.log(error);
        }
    );
  }

However if I run the Application I get following error:

Http failure response for http://localhost:4200/testdata/csv/test.csv: 404 Not Found

The .csv is in this folder: src > app > testdata > csv > test.csv

The api.service.ts in which I the Method is written here: src > app > api.service.ts

I am running the Method in the testdata.component.ts which lays here: src > api > testdata > testdata.component.ts

with following code:

  ngOnInit() {
   this.apiService.readCsv();
  }

What am I doing wrong? Why do I get a 404 Not Found Error? How could I correctly read the file and even display it?

Upvotes: 0

Views: 1718

Answers (2)

Federico López
Federico López

Reputation: 74

This has to do with what happens when you run ng serve. Your implementation its build over the assumption that ng serve will start a Web Server in your src/app directory and that is not what actually happens. What is happening (as described in this question) is that ng serve compiles your app and starts a local server using webpack-dev-server.

By default the only directory included in the build to deploy is the assets directory under src/assets. You can change that in the assets section of your project in the angular.json file.

{
 ...
 "project": {
   "<project-name>": {
         "architect": {
              "build": {
                "assets": [<list of paths>]
                 ...

See this stackblitz example.

Upvotes: 1

Pablo
Pablo

Reputation: 61

Files outside of "assets" folder are not available by default. Save your file inside your project's "assets" folder and access it like this:

this.httpClient.get('assets/test.csv', {responseType: 'text'}).....

Otherwise you would have to make your folder available in the '"assets":' section of your angular.json file.

Upvotes: 3

Related Questions