0

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?

1
  • Mime type error perhaps? An alternative could be to have an actual endpoint that reads and returns the contents of the file. Commented Aug 29, 2019 at 9:01

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.