【问题标题】:Make http call into for loop Angular2使http调用for循环Angular2
【发布时间】:2017-11-22 12:32:05
【问题描述】:

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

【问题讨论】:

  • 为什么你的 cmets 没有直接加载到 post 对象中?
  • 另外,为什么你认为这不是要走的路?
  • 不是这样,因为应用程序只是在加载而不给出任何响应。
  • 那么你应该在你的帖子加载时触发对 cme​​ts 的请求。这很简单,但您需要显示(最小的相关部分)您的组件代码和相关服务。
  • @bryan60 这是代码:this.commonService.getMethod('posts').then((data) => { this.posts = data.result }).catch((error) = > { })

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


【解决方案1】:

在你的组件内部

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

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

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

举例说明我是怎么做的。

【讨论】:

  • 但最好的办法是创建另一个组件名称“cmets”传递到可观察对象或请求本身,让组件处理你,这也是一个好习惯。
  • 可能是更好的方法,但我现在想简单一点
  • 在那里做过。简单的方法是正确地做。它的代码多了几行,但它会很好地工作。我添加了一个屏幕截图,向您展示了我在我的应用中所做的事情。
  • @RayLuxembourg 我想你的意思是{{myCall(post._id) | async}}(一个|)。
  • @Pac0 是的,抱歉。
猜你喜欢
  • 2018-11-07
  • 1970-01-01
  • 2013-12-26
  • 1970-01-01
  • 2016-01-16
  • 1970-01-01
  • 2016-04-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多