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

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


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