我有一个应用程序,用户可以在其中添加评论,并且会显示评论,我的问题是刷新页面之前不会显示评论。
我希望在用户单击“输入”或“提交”按钮后显示评论
这是我到目前为止所拥有的:
获取数据service.ts
this.activeRouter.params.subscribe((params) => { let id = params['id']; this.moviesService.getComments(id) .then(comments => { console.log(comments); this.comments = comments; }); });
2.然后显示到前端:html
<div *ngFor="let comment of comments" class="col-md-7">
<ul class="list-group">
<li class="list-group-item">Author: {{comment.author}}</li>
<li class="list-group-item">Comments: {{comment.description}}</li>
</ul>
<br>
</div>
不幸的是,当我的服务器更新 JSON 时,html 根本不会更新,直到我刷新页面,然后我才能看到添加的评论错误
为了实现我想要的目标,我的代码中缺少什么?虽然是新手
最佳答案
您的代码很好,但不幸的是 Promise 只能解析为一个值。
但是,可观察量可以为您提供实时数据流!
使 movieService.getComments() 方法返回一个返回评论的可观察对象。
它应该看起来像这样(假设您正在使用 Angular HttpClient 来获取评论):
// movieService.service.ts
import { HttpClient } from '@angular/common/http'
...
constructor(
private http: HttpClient
)
getComments() {
return this.http.get<Comments>(url)
}
...
你可以像这样使用可观察的:
// comment.component.ts
...
comments: Observable<Comments>
...
ngOnInit() {
this.comments = this.movieService.getComments()
}
...
最后在模板中:
// comments.component.html
<div *ngFor="let comment of comments | async" class="col-md-7">
<ul class="list-group">
<li class="list-group-item">Author: {{comment.author}}</li>
<li class="list-group-item">Comments: {{comment.description}}</li>
</ul>
<br>
</div>
关于javascript - Angular 6 : Real time data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50996436/