Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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}`);
            }
        }
    );
like image 587
yogihosting Avatar asked Nov 01 '17 10:11

yogihosting


People also ask

What is HttpClient in angular?

What Is HttpClient? HttpClient is a built-in service class available in the @angular/common/http package. It has multiple signature and return types for each request. It uses the RxJS observable-based APIs, which means it returns the observable and what we need to subscribe it.


2 Answers

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());
})
like image 128
Chandru Avatar answered Oct 16 '22 13:10

Chandru


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.

like image 20
nsk Avatar answered Oct 16 '22 14:10

nsk