Angular 4: How to Read Content of Text File With Httpclient

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

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: How to download a file from HttpClient?

Try something like this:

type: application/ms-excel

/**
* used to get file from server
*/

this.http.get(`${environment.apiUrl}`,{
responseType: 'arraybuffer',headers:headers}
).subscribe(response => this.downLoadFile(response, "application/ms-excel"));


/**
* Method is use to download file.
* @param data - Array Buffer data
* @param type - type of the document.
*/
downLoadFile(data: any, type: string) {
let blob = new Blob([data], { type: type});
let url = window.URL.createObjectURL(blob);
let pwa = window.open(url);
if (!pwa || pwa.closed || typeof pwa.closed == 'undefined') {
alert( 'Please disable your Pop-up blocker and try again.');
}
}

Angular2 get content from txt file via http

Within the new HttpClient, the default response type is JSON, so it will try to parse it as such. Instead of calling .text(), you now need to specify the return type of text like so:

this.http.get('http://test.torbengabriel.de/data/articles/article.txt', {responseType: 'text'}).subscribe(data => {
console.log('data', data);
});


Related Topics



Leave a reply



Submit