【发布时间】: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 对象中?
-
另外,为什么你认为这不是要走的路?
-
不是这样,因为应用程序只是在加载而不给出任何响应。
-
那么你应该在你的帖子加载时触发对 cmets 的请求。这很简单,但您需要显示(最小的相关部分)您的组件代码和相关服务。
-
@bryan60 这是代码:this.commonService.getMethod('posts').then((data) => { this.posts = data.result }).catch((error) = > { })
标签: angular angular2-template angular2-forms angular2-directives angular-universal