38

I have a .txt file in my Angular 4 project directory and I want to read its content. How to do it ? Below is the code which I employed.

The file is in 'files' folder which is inside the 'app' folder. The component where i have HTTPClient code is in 'httpclient' folder which is inside 'app' folder.

Meaning 'files' folder and 'httpclient' folder are children.

The code is shown below. It not working as i m getting 404 error - 'GET http://localhost:4200/files/1.txt 404 (Not Found)'

this.http.get('/files/1.txt').subscribe(data => {
        console.log(data);
    },
        (err: HttpErrorResponse) => {
            if (err.error instanceof Error) {
                // A client-side or network error occurred. Handle it accordingly.
                console.log('An error occurred:', err.error.message);
            } else {
                // The backend returned an unsuccessful response code.
                // The response body may contain clues as to what went wrong,
                console.log(`Backend returned code ${err.status}, body was: ${err.error}`);
            }
        }
    );
9
  • Have you tried a relative URL? (i.e. http.get('files/1.txt') -- no initial slash) Or placing the files in the assets folder, the content of which - I believe - is copied as is at the root of the site. Commented Nov 1, 2017 at 11:09
  • yes i tried it just now, same error. It is not finding it - 404. what's wrong? I am just following the codes of official angular docs angular.io/guide/http#requesting-non-json-data Commented Nov 1, 2017 at 11:12
  • your file path is correct ? Commented Nov 1, 2017 at 11:20
  • yes file path is correct. Even if i move the text file to the same folder of teh component and do this.http.get('./1.txt') i get the same error. Commented Nov 1, 2017 at 11:23
  • 1
    @yogihosting it's not working because when the CLI builds the project with ng serve it only processes .ts, .html and .css files. Static assets like .txt files do not belong in your code and they are dropped by ng serve. Commented Nov 2, 2017 at 10:32

5 Answers 5

37

Try like this :

this.http.get('app/files/1.txt').subscribe(data => {
    console.log(data.text());
})

The CLI can't access docments inside the app directory your project. if you move to text document you can access the text file like assets/1.txt.

if you want to access document inside the app directory you need to add path in assets array in the .angular-cli.json

.angular-cli.json

"assets": [
  "assets",
  "app", /* add this line to access document inside the app directory */
  "favicon.ico"
]

here below is my example try like this :

this.http.get('app/home/1.txt').subscribe(data => {
    console.log('data', data.text());
})
Sign up to request clarification or add additional context in comments.

5 Comments

Yes assets files are accessible but How I can assess files kept in separate folder?
you need to add app in the angular-cli.json file inside the assets array . then you can access it. and import is re-run the project
I added app to the angular-cli.json, its still not working.
@yogihosting After add app inside the assets array. you need to Re-run the project or Restart the project
you are just great! I have to restart my angular project. I was using vs code. So i closed it and reopened it and ran the app once more. Now I am able to asses it. The code here is this.http.get('app/files/1.txt', {responseType: 'text'})
24

Angular 6/7

{ responseType: 'text' as 'json'}

for now works

this.http.get("app/files/1.txt", { responseType: 'text' as 'json'}).subscribe(data => {
    console.log(data.text());
})

Refer to this ticket on GitHub for the complete discussion.

Comments

4

Just one correction to the previous answer: add "responseType: 'text'" to the options:

this.http.get("app/files/1.txt", "{ responseType: 'text' }").subscribe(data => {
    console.log(data.text());
})

1 Comment

Here, in January 2020, text() method must be removed... if so, this code works.
3

This is tested in Angular 6

Create a service using

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http'; 
//Read  text file
export interface ResultJson{

}
@Injectable({
  providedIn: 'root'
})
export class TestService {
  urlEncoded = '/Test.text';
  getText(){
    return this.http.get(this.urlEncoded, {responseType: 'text'});
  }
}

and call the service in your component like below

  resultJSON: ResultJson;
  ResultJsonString : any;
this
    .testService
    .getText()
    .subscribe((data:ResultJson) => {
         this.ResultJsonString = data;
       });

Hopefully this helps

Comments

2

I was able to get a local file(JSON) with Angular 6 project.

Project strucuture:

|-src
|--app
|---core
|---...
|---app.module.ts
|--assets
|...

Steps:

1) Inside angular.json I've added the folder where I put the file:

 "projects": {
    "my-project": {
      "root": "",
      "sourceRoot": "src", // ** my project root is "src" folder
      "projectType": "application",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            // ...
            "assets": [
              "src",         // <--- ADDED THIS
              "src/assets",
              "src/favicon.ico",
              "src/manifest.json",
              "src/robots.txt",
              "src/web.config"
            ]

2) Wrote following service to get the file:

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

@Injectable({
   providedIn: 'root'
})
export class EnvironmentService {
   constructor(private readonly _httpClient: HttpClient) {
   }

   public init(): Promise<any> {       
      return new Promise(resolve =>
         this._httpClient
         .get('file.json')
         .first()
         .subscribe((data: any) => {
            // data from JSON
            resolve()
         })
      )
   }
}

Bonus:
In case if you want to read custom environment variables(besides what standard Angular one provides) you can add above service into App.module.ts:

export function init_app(appLoadService: EnvironmentService): () => Promise<any> {
  return () => appLoadService.init()
}

@NgModule({
  // ...
  providers: [
    EnvironmentService,
    { provide: APP_INITIALIZER, useFactory: init_app, deps: [ EnvironmentService ], multi: true },
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule {
}

P.S. In case of issues you can check this one.

4 Comments

Working with a Angular 6 app as well, followed your solution, but wasn't able to retrieve the JSON successfully. I created: Angular 6: HttpClient Get JSON File 404 Error To clarify my situation.
Shared an answer in your post: stackoverflow.com/a/50986804/806202 I hope it will help.
where do you put your file.json ?
In the application source (src/) folder.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.