Angular EventEmitter does not emit any changes of an array

1.2k Views Asked by At

here is my code:

notes.service.ts

      private notes: Array<Note> = [];
      notesChanged = new EventEmitter<Note[]>();
     
      getNotes() {
        this.getData();
        console.log('getNotes()', this.notes);
        return this.notes;
      }

      getData() {
         this.http.get<Note[]>(this.url).subscribe(
            (data) => {
                 this.notes = data;
                 this.notesChanged.emit(this.notes);
            }
         );
      }

notes.component.ts

      notes: Array<Note> = [];
 
      ngOnInit(): void {
          this.notes = this.notesData.getNotes();
          this.notesData.notesChanged.subscribe(
              (notes: Note[]) => this.notes = notes
          );
      }

notes.component.html

<div *ngFor="let item of notes" class="col-md-4">
   <a [routerLink]="['/note', item.id]" class="note-link">
      <div class="note-body text-center">
          <h4>{{item.title}}</h4>
          <p>{{item.text}}</p>
      </div>
   </a>
</div>

Notes are not displayed after loading in browser, only if I navigate away and then go back to notes, only then they will be displayed.

console.log('getNotes()', this.notes); shows that the array is empty right after loading in browser.

2

There are 2 best solutions below

0
Eldar Scott On BEST ANSWER

The problem is with the getNotes() method. It sends an asynchronous request by calling getData(), does not wait for the result and can return either an empty list (if it didn't have time to be completed) or data from the server (what you see by browsing sometimes). The way for you to go is to return notes in getData() after subscribtion.

1
Duki On

console.log('getNotes()', this.notes); is triggered before the getData call to the api gets the results. That's why you don get anything in the log on page load.

Can you show the notes.component.html?