我有一个应用程序,用户可以在其中添加评论,并显示评论,我的问题是,评论不会显示,直到我刷新页面。
我希望在用户单击enter或submit按钮后显示评论
这是我到目前为止所知道的:
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根本不会更新,直到我刷新页面,然后我才能看到添加的注释错误的。
为了实现我想要的东西,我在代码中遗漏了什么?新手
发布于 2018-06-23 07:25:39
您的代码很好,但不幸的是,Promise只能解析为一个值。
但是,可观察性可以为您提供实时数据流!
使moviesService.getComments()方法返回一个返回注释的observable。
它应该看起来有点像这样(假设您正在使用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>
发布于 2020-10-11 22:07:04
在Angular中使用Async Pipes & Observables管道就像在Linux中使用管道一样。它们接受输入并产生输出。输出结果由管道的功能决定。此管道接受promise或observable作为输入,并且每当promise解析或observable发出一些新值时,它都可以更新模板。与所有管道一样,我们需要在模板中应用管道。
让我们假设我们有一个API返回的产品列表,并且我们有以下可用的服务:
// api.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class ApiService {
constructor(private http: HttpClient) { }
getProducts() {
return this.http.get('http://localhost:3000/api/products');
}
}
上面的代码很简单-我们指定了返回HTTP GET调用的getProducts()方法。
是时候在组件中使用此服务了。我们在这里要做的是创建一个Observable,并将getProducts()方法的结果赋给它。此外,我们将每隔1秒调用一次,因此如果API级别有更新,我们可以刷新模板:
// some.component.ts
import { Component, OnInit, OnDestroy, Input } from '@angular/core';
import { ApiService } from './../api.service';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/interval';
import 'rxjs/add/operator/startWith';
import 'rxjs/add/operator/switchMap';
@Component({
selector: 'app-products',
templateUrl: './products.component.html',
styleUrls: ['./products.component.css']
})
export class ProductsComponent implements OnInit {
@Input() products$: Observable<any>;
constructor(private api: ApiService) { }
ngOnInit() {
this.products$ = Observable
.interval(1000)
.startWith(0).switchMap(() => this.api.getProducts());
}
}
最后但同样重要的是,我们需要在模板中应用异步管道:
<ul>
<li *ngFor="let product of products$ | async">{{ product.prod_name }} for {{ product.price | currency:'£'}}</li>
</ul>
这样,如果我们将一个新项推送到API (或移除一个或多个项),更新将在1秒内在组件中可见。
https://stackoverflow.com/questions/50996436
复制相似问题