简体   繁体   中英

Angular 4: How to read content of text file with HTTPClient

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 im 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}`);
            }
        }
    );

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());
})

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.

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());
})

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

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 {
}

PS In case of issues you can check this one .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM