[英]UI is not updated when the data is available, using Angular
I'm working on my master degree and i have a bug.我正在攻读硕士学位,但我有一个错误。 I'm pretty sure it's something easy but i can't figure it out.
我很确定这很容易,但我无法弄清楚。 I'm working with Angular, Firestore and RxJs for it.
我正在与 Angular、Firestore 和 RxJs 合作。 The big problem is that the ui is not updated.
最大的问题是ui没有更新。 On init of the page, the array with my infos is empty and in a short time, it is filled with a new comment exactly as expected.
在页面初始化时,包含我的信息的数组是空的,并且在很短的时间内,它完全按照预期填充了一条新评论。
So, i have a parent component, university.html
:所以,我有一个父组件
university.html
:
<div *ngIf="reviewsData.length > 0">
<app-editable-comments
*ngFor="let review of reviewsData"
[review]="review">
</app-editable-comments>
And the child component app-editable-comments.html
which only render the infos to the screen.子组件
app-editable-comments.html
仅将信息呈现到屏幕上。
I'm getting the data in university.ts
using ngOnInit
:我正在使用
ngOnInit
在university.ts
中获取数据:
this.firebaseService.getReviewsData().subscribe(data => {
this.reviewsData = [];
data.forEach(review => {
const reviewDetails = new ReviewData(review);
if (reviewDetails.universityId === this.universityId) {
this.reviewsData.push(reviewDetails);
}
});
});
Until now everything it's fine.直到现在一切都很好。 But there is another function which is called in
ngOnInit
as well:但是还有另一个 function 也在
ngOnInit
中调用:
if (this.user.id && this.universityId) {
this.showAddNewComment();
this.changeDetectorRef.markForCheck(); // i tried it and is not working
}
The showAddNewComment()
method it's only verifying if the array with the reviews already have a review from logged user or it needs to add a new one to initialize a new comment: showAddNewComment()
方法只验证带有评论的数组是否已经有来自登录用户的评论,或者它需要添加一个新评论来初始化新评论:
showAddNewComment() {
if (this.reviewsData.filter((item: ReviewData) => item.userId === this.user.id).length === 0) {
const newCommentForPresentLoggedInUser = {
universityId: this.universityId,
userId: this.user.id,
date: new Date()
};
this.reviewsData.push(new ReviewData(newCommentForPresentLoggedInUser));
}
}
Any ideas?有任何想法吗? I'm trying to fix this from a long time...
我试图解决这个问题很长一段时间......
while working with Angular and change detection it's always better to not edit data implace in showAddNewComment u are doing it在使用 Angular 和更改检测时,最好不要在 showAddNewComment 中编辑数据,你正在这样做
i think u should do it like this.我认为你应该这样做。
showAddNewComment() {
let newArray = [...this.reviewsData]
if (this.reviewsData.filter((item: ReviewData) => item.userId === this.user.id).length === 0) {
const newCommentForPresentLoggedInUser = {
universityId: this.universityId,
userId: this.user.id,
date: new Date()
};
newArray.push(new ReviewData(newCommentForPresentLoggedInUser));
}
this.reviewsData = newArray;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.