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

angular read file from assets
angular read file from disk
typescript read text file
angular 4 read local file
read and write file in angular 4
angular 8 read file content
ionic 4 read local json file
angular read text file line by line

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 => {
        (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 => {

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


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

here below is my example try like this :

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

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​  You can use the HttpClient service in Angular 4 to read and extract data from an external JSON file. Using the Get() method of HttpClient class, you can easily open and read data from a JSON file. Here in this post, I am sharing a simple example on how to read JSON data from a file and convert the data to an HTML table.

Angular 6/7

{ responseType: 'text' as 'json'}

for now works

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

Refer to this ticket on GitHub for the complete discussion.

How To Read Local JSON Files In Angular, We can import or read local JSON files in Angular,several different ways One more thing you need to understand is the the imported JSON file contents are typesafe. So if you tried to change the version to string it will throw error. 5 or Angular 4 to read local json files, we need to use HttpClient from  Implementing file save functionality with Angular 4 Today, I faced a requirement where I need to implement file save functionality in an Angular 4 application. In this quick post, I will show you how to implement this functionality in Angular 4 using FileSaver.js module.

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

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

Angular 6 (TypeScript) read content from file in assets directory , Angular 6 (TypeScript) read content from file in assets directory read from the file (basically mock the call to the backend) but for the life of me, I can't seem to read from the file (sitting in the assets folder) and put the contents into a string to pass to the frontend import { HttpClient } from '@angular/common/http'; // and then:  HttpClient is introduced in Angular 4.3, If you are using Angular version 4.3 below use the below method to read the JSON files Reading local JSON files in Angular 2+ versions We need to use Http from “@angular/http” to import JSON files in Angular version 4.3 below and Angular 2 +.

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

Project strucuture:



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

2) Wrote following service to get the file:

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

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

   public init(): Promise<any> {       
      return new Promise(resolve =>
         .subscribe((data: any) => {
            // data from JSON

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

  // ...
  providers: [
    { 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.

Read an External JSON file in Angular 4 and Convert Data to HTML , You can use the HttpClient service in Angular 4 to read and extract data from an external JSON file. Read JSON Data from File and Bind it to an HTML Table in Angular 4 and its properties, which we need to access files in the server and read its contents. arrBirds = data as string []; // FILL THE ARRAY WITH DATA. I've been trying to figure out how to read the contents of a httpclient call, and I can't seem to get it. The response status I get is 200, but I can't figure out how to get to the actual Json being

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{

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

and call the service in your component like below

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

Hopefully this helps

Communicating with backend services using HTTP, The HttpClient in @angular/common/http offers a simplified client HTTP API for Angular For example, the app might need a configuration file on the server, reads a text file from the server and logs the file contents, before returning those  HttpClient does not retrieve API that returns plain text. HttpClient cannot set responseType: 'text' as Get options as described in the documentaion. Expected behavior. It should be able to accept plain text from API response.

HttpClient not able to retrieve plain text · Issue #18672 · angular , [x ] bug report => search github for a similar issue or PR before submitting HttpClient cannot set responseType: 'text' as Skip to content Edit file http.d.​ts Read more about our automatic conversation locking policy. Read response headers from API response - Angular 5 + TypeScript Another way is we can add code as below in the webApiconfig.cs file. Angular 4.3.3 HttpClient

3 Methods for Reading Local JSON Files in Angular 7/8, The second method that you can use to import JSON files in your Angular application is Angular HttpClient . Let's see this by example. First, you  Angular 4.3 brings us a new easier way to handle http requests with the HttpClient library. It’s available under a new name to avoid causing breaking changes with the current Http library. HttpClient also gives us advanced functionality like the ability to listen for progress events and interceptors to monitor or modify requests or responses.

Loading Text File Content With FileReader During A Drag-And-Drop , For the last few weeks, I've been digging into file-handling in Angular 7. First, with the uploading of single files using the HttpClient service; and then, read-in the contents of a Text File that was dragged-and-dropped onto my  We are required to import and setup HttpClient service in Angular project to consume REST APIs. To work with HttpClient service in Angular, you need to import the HttpClientModule in app.module.ts file. Then inject HttpClient service in constructor method after that you can hit the remote server via HTTP’s POST, GET, PUT and DELETE methods.

  • 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.
  • 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
  • your file path is correct ?
  • 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.
  • @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.
  • 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'})
  • Here, in January 2020, text() method must be removed... if so, this code works.
  • 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: I hope it will help.