将http调用转换为for循环Angular2

时间:2017-11-22 12:32:05

标签: angular angular2-template angular2-forms angular2-directives angular-universal

如何在Angular2中的for循环中调用每个项目的最佳方法

<div class="post" *ngFor="let post of posts">
  Title: {{post.title}}   
  Comments: {{getCommentsForPostID(post._id)}}
</div>

我不认为这是这样做的,所以我需要另一种解决方案。

更新

getCommentsForPostID(post_id) {
  this.commonService.getMethod('posts/' + post_id + '/comments').then((data) => {
    return data.result
  }).catch((error) => {
   return null
  })
}

加载帖子的代码:

this.commonService.getMethod('posts').then((data) => {
  this.posts = data.result
}).catch((error) => {

})

我用于http请求的公共服务:

getMethod(path) {
  return this.http.get(this.api + path, { headers: this._makeHeaders() 
  }).toPromise().then((response) => {
   return response.json();
  }).catch(this.handleError);
}

1 个答案:

答案 0 :(得分:1)

在您的组件内

myCall(param){ return http.get(someUrl + param).map(res=>res.json())}

在您的html中,您可以使用async来解析请求

  Comments: {{myCall(post._id) | async}}

示例我是如何做到的。

enter image description here