0

Problem is: When I start this component, my ngFor div always updates and my RAM becomes empty. As I know, ngFor updates when array is updated, but my array(announcements) update only once, in constructor. I have two ngFor divs:

<mat-tab label="Classroom"> 
        <div *ngFor="let announcement of announcements">
            <mat-card class="example-card">
                <mat-card-header>
                    <mat-card-subtitle>{{"Announcement: " + announcement.text}}</mat-card-subtitle>
                </mat-card-header>
                <mat-card-footer>
                    <div *ngFor="let comment of loadComments(announcement)">
                        <mat-card class="example-card comment">
                            <mat-card-header>
                              <mat-card-subtitle>{{"Comment: " + comment.text}}</mat-card-subtitle>
                            </mat-card-header>
                            <mat-card-content>
                        </mat-card>
                    </div>
                </mat-card-footer>
            </mat-card>
        </div>
    </mat-tab>

ts file:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { environment } from 'src/environments/environment';
import { Announcement } from '../model/announcement';
import { Classroom } from '../model/classroom';
import { User } from '../model/user';
import { Comment } from '../model/comment';
import { ClassroomService } from '../service/classroom.service';
import { CommentService } from '../service/comment.service';
import { AnnouncementService } from '../service/announcement.service';

@Component({
  selector: 'app-view-classroom',
  templateUrl: './view-classroom.component.html',
  styleUrls: ['./view-classroom.component.css']
})
export class ViewClassroomComponent implements OnInit {

  announcements: Announcement[] | undefined;
  comments: Comment[] | undefined;

  constructor(private classroomService: ClassroomService,
              private commentService: CommentService,
              private announcementService: AnnouncementService,
              private formBuilder: FormBuilder) 
  {
    this.classroomService.getClassroomUsers(JSON.parse(localStorage.getItem(environment.classroom) || ''), 'teachers').subscribe(
      (response: User[]) => this.teachers = response);
    this.classroomService.getClassroomUsers(JSON.parse(localStorage.getItem(environment.classroom) || ''), 'students').subscribe(
      (response: User[]) => this.students = response);
    this.classroomService.getClassroomOwner(JSON.parse(localStorage.getItem(environment.classroom) || '')).subscribe(
      (response: User) => this.owner = response);
    this.classroom = JSON.parse(localStorage.getItem(environment.classroom) || '');
    this.announcementService.getAnnouncementsByClassroom(JSON.parse(localStorage.getItem(environment.classroom) || '')).subscribe(
      (response: Announcement[]) => this.announcements = response);
  }

  ngOnInit(): void {
    
  }

  loadComments(announcement: Announcement){
    let an = announcement;
    this.commentService.getCommentsByAnnouncement(an).subscribe(
      (response: Comment[]) => this.comments = response);
    return this.comments;
  }

}

But when i remove inner ngFor, problem is gone. What should i do?

2
  • 2nd one is an async call which might be causing issue, I would suggest use async pipe. Jan 15 at 13:15
  • @VimalPatel Im not so good in this) Can you show me some example? Jan 15 at 14:16
1

What you are doing is wrong.

  loadComments(announcement: Announcement){
    let an = announcement;
    this.commentService.getCommentsByAnnouncement(an).subscribe(
      (response: Comment[]) => this.comments = response);
    return this.comments; // <-- old values!!
  }

As it is right now this metod will return an old version of this.comments, not the one from the response.

Change the metode like this:

  loadComments(announcement: Announcement):Observable<Comment[]>{
    let an = announcement;
    return this.commentService.getCommentsByAnnouncement(an);
  }

And in the html file:

<ng-container *ngIg="loadComments(announcement) | async as comments"> 
    <div *ngFor="let comment of comments">
    ...
    </div>
</ng-container>
1
  • Wow, great, it helps me a lot, you are the best! Jan 16 at 14:11
1

You're seeing this issue as the data is populating asynchronously. To resolve this, one of solution is to apply reactive programming strategy using RxJs.

Step 1: Replace static array definition to a Subject (import from 'rxjs')

announcements: Announcement[] | undefined;
comments: Comment[] | undefined;

// above two line needs to be changed to

announcements$: Subject<Announcement[] | undefined>;
comments$: Subject<Comment[] | undefined>;

Step 2: Update assignments

this.announcementService.getAnnouncementsByClassroom(
  JSON.parse(localStorage.getItem(environment.classroom) || '')
).subscribe(
  // (response: Announcement[]) => this.announcements = response <- update this to:
  (response: Announcement[]) => this.announcements$.next(response)
);

this.commentService.getCommentsByAnnouncement(an).subscribe(
  // (response: Comment[]) => this.comments = response <- update this to:
  (response: Comment[]) => this.comments$.next(response)
);
// return this.comments; <- this is not required any more

Step 3: Update HTML

<!-- old -->
<div *ngFor="let announcement of announcements">
<!-- new -->
<div *ngFor="announcements$ | async as announcement">

<!-- old -->
<div *ngFor="let comment of loadComments(announcement)">
<!-- new -->
<div *ngFor="comments$ | async as comment">
2
  • It helps, but i still dont know how to update this comments$ for each announcement. When i tried smth like {{loadComments(announcement$}} it happens again. Jan 15 at 15:12
  • Can you create a working demo on Stackblitz and share the link? Maybe I could help more after looking at demo!! Jan 15 at 15:31
0

just change

*ngFor="let comment of loadComments(announcement)"

to

*ngFor="let comment of comments"

and

loadComments(announcement: Announcement) {
    this.commentService.getCommentsByAnnouncement(announcement).subscribe((response: Comment[]) => {
        this.comments = response
    })
}
1
  • But i need to get new array of comments for every announcement. In this situation, i will update my comments array only once. Jan 15 at 14:10

Not the answer you're looking for? Browse other questions tagged or ask your own question.