【发布时间】:2020-12-17 19:09:17
【问题描述】:
有人可以帮我解决这个问题吗? 我开始学习 angular8 中的 observables 和异步管道。
我正在尝试向我的 observable 添加一个元素并更新我的 UI。 此刻我有这个,它在我的数组的开头和结尾添加了我的元素。 我做错了什么?
在我的组件中:
var comment = new Comment();
this.postService.addComment(commentdto).subscribe((c) => {
comment = c;
this.post.subscribe(x => {
x.comments.push(comment);
this.post = of(x);
});
});
<div *ngIf="post | async as p">
<div class="post-container border-bottom border-dark mb-2">
<h3 class="col-sm-12">{{p.text}}</h3>
<div class="col-sm-12">
<img class="img-fluid image-height" src="https://localhost:5003/posts/{{p.imageUrl}}" />
<div class="row" style="margin-left: 0px; margin-top: 2%">
<a style="margin-right:15px" class="pointer" (click)="vote(true, post)"><i class="fas fa-thumbs-up"></i> {{p.upVotes}}</a>
<a style="margin-right:15px" class="pointer" (click)="vote(false, post)"><i class="fas fa-thumbs-down"></i> {{p.downVotes}}</a>
</div>
</div>
</div>
<h5>Comments:</h5>
<div class="form-group mb-3">
<textarea [(ngModel)]="addComment" class="form-control" aria-label="With textarea" placeholder="Add comment..."></textarea>
</div>
<div>
<button type="button" class="btn btn-primary ml-auto" (click)="addCommentToPost()">Post</button>
</div>
<div *ngFor="let c of p.comments" class="container">
<div class="row comment-bubble">
{{c.text}}
</div>
</div>
</div>
服务:
addComment(comment: EditComment): Observable<Comment> {
return this.http.post<Comment>(`${this.baseUrl}/AddComment`, comment, this.httpOptionsAuthentication)
.pipe(catchError(this.handleError));
}
handleError(error) {
let errorMessage = '';
if (error.error instanceof ErrorEvent) {
// client-side error
errorMessage = `Error: ${error.error.message}`;
} else {
// server-side error
errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
}
console.log(errorMessage);
return throwError(errorMessage);
}
【问题讨论】:
-
你的 post 变量是可观察的吗?我不明白为什么您需要在另一个内部观察到。只需 x.cmets.push(c) 在第一个可观察对象内就足够了。我假设您需要在 html 部分循环通过 x 而不是 p。
-
是的,这是一个可观察的
-
不需要。 Post 服务正在添加评论,它已经是一个 http observable。除非你使用外观部分,否则没有理由在 observable 中添加 observable
标签: angular angular-observable async-pipe