我有一个应用程序,其中用户可以添加注释,并显示注释,我的问题是注释不显示,直到我刷新页面.
这是我到目前为止:
>获取数据服务
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根本没有更新,直到我刷新页面然后我可以看到添加的注释错误
我的代码中缺少什么来实现我想要的?新手虽然
解决方法:
但是,observables可以为您提供实时数据流!
使moviesService.getComments()方法返回一个返回注释的observable.
它应该看起来像这样(假设你使用角度HttpClient来获取注释):
// movieService.service.ts
import { HttpClient } from '@angular/common/http'
...
constructor(
private http: HttpClient
)
getComments() {
return this.http.get<Comments>(url)
}
...
您可以像这样使用observable:
// 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>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。