简体   繁体   English

Angular 4-5 HttpClientModule显示数据

[英]Angular 4-5 HttpClientModule display data

With HttpModule I used this code to get data from Express.js REST API: 使用HttpModule,我使用此代码从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. 现在,使用HttpClientModule,我无法弄清楚如何做到这一点。 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. 但它不起作用。

HttpClientModule works almost the same as the older HttpModule . HttpClientModule工作方式与旧的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: HttpClient的默认responseTypejson ,因此您可以跳过将响应转换为json的步骤,而是像以前一样直接使用您的响应:

this.httpClient.get('http://localhost:3000/api/articles')
    .subscribe(data => this.results = data); // result is passed directly

HttpClient works best when you cast the returned data. 在转换返回的数据时,HttpClient的效果最佳。 See this link where a complete mini project is setup to show how to get and display data. 请参阅此链接 ,其中设置了完整的迷你项目,以显示如何获取和显示数据。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM