Torben G
Torben G

Reputation: 800

Angular2 get content from txt file via http

I want to get a simple text from a file on my webserver ( Text File )

This is my http call:

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

I got an error (but with a status code 200):

error: SyntaxError: Unexpected token K in JSON at position 0 at JSON.parse (<anonymous>) at XMLHttp…, text: "Kommen wir nun einmal zu einigen Hilfsmitteln, mit… das

So he gets the file. The Text ("Kommen wir nun einmal...") is correct. But the console.log will never be called and i cannot work with the data. What is my mistake? I hope someone could help me. Thanks

Upvotes: 0

Views: 785

Answers (1)

user184994
user184994

Reputation: 18281

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

Upvotes: 1

Related Questions