我有一个应用程序,用户可以添加评论,并显示评论,我的问题是评论不显示,直到我刷新页面。
我希望在用户单击“仅输入”或“提交”按钮后显示注释
以下是我目前掌握的情况:
获取数据服务.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根本不会更新,除非我刷新页面,然后我可以看到添加的注释是错误的
我的代码中缺少什么来实现我想要的?不过是新手

最佳答案

你的代码是好的,但不幸的是,一个承诺只能解决一个价值。
然而,可观测数据可以为你提供一个实时的数据流!
使moviesService.getComments()方法返回返回注释的observate。
它应该看起来有点像这样(假设您正在使用角度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>

07-28 05:02