当数据可用时,不使用Angular更新UI

发布时间:2020-07-07 16:28

我正在攻读硕士学位,但有一个错误。我很确定这很容易,但是我不知道。我正在为此使用Angular,Firestore和RxJs。最大的问题是用户界面未更新。在页面初始化时,包含我的信息的数组为空,并且在很短的时间内,该数组将完全按照预期填充新的注释。

因此,我有一个父级组件university.html

<div *ngIf="reviewsData.length > 0">
      <app-editable-comments
      *ngFor="let review of reviewsData"
      [review]="review">
</app-editable-comments>

还有子组件app-editable-comments.html,该子组件仅将信息呈现到屏幕上。
我正在使用university.tsngOnInit中获取数据:

this.firebaseService.getReviewsData().subscribe(data => {
          this.reviewsData = [];
          data.forEach(review => {
            const reviewDetails = new ReviewData(review);
            if (reviewDetails.universityId === this.universityId) {
              this.reviewsData.push(reviewDetails);
            }
          });
        });

直到现在一切都很好。但是还有一个ngOnInit也被调用的函数:

if (this.user.id && this.universityId) {
        this.showAddNewComment();
        this.changeDetectorRef.markForCheck(); // i tried it and is not working
}

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));
    }
  }

有什么想法吗?我正试图解决很长时间……

回答1

在使用Angular和变更检测时 最好不要编辑数据 在showAddNewComment中,您正在这样做

我认为你应该这样做。

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;
  }
updating 相关推荐