1

With HttpModule I used this code to get data from Express.js REST API:

getArticles() {
  this.http.get('http://localhost:3000/api/articles')
    .map(res => res.json()).subscribe(res => this.articles = res);
}

After that I would display the result in the template using binding.

Now, with HttpClientModule, I can't figure out how to do that. The documentation suggests using something like

this.httpClient.get('http://localhost:3000/api/articles')
  .subscribe(data => { this.results = data['results']; });

But it doesn't work.

mikebrsv
  • 1,890
  • 2
  • 24
  • 31

3 Answers3

1

HttpClientModule works almost the same as the older HttpModule. The default responseType for HttpClient is json, so you would skip the step of converting your response to json and instead use your response directly like you did before:

this.httpClient.get('http://localhost:3000/api/articles')
    .subscribe(data => this.results = data); // result is passed directly
Christian Santos
  • 5,386
  • 1
  • 18
  • 24
1

HttpClient works best when you cast the returned data. See this link where a complete mini project is setup to show how to get and display data.

mohsenmadi
  • 2,277
  • 1
  • 23
  • 34
1

this.httpClient.getArticles().subscribe(data => this.results = data);

Akash
  • 9
  • 3