有人可以帮我解决这个问题吗?我开始学习 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);
}