The Angular EventEmitter does not broadcast any modifications made to an array

Below is the code snippet:

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>

The issue I am facing is that notes are not displayed after loading in the browser. They only appear if I navigate away and then go back to the notes section.

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

Answer №1

The issue lies within the getNotes() function. It makes an asynchronous call to getData(), does not wait for the response, and can either return an empty list (if it's not completed) or data from the server (which might appear sporadically). To fix this, you should return notes in getData() after subscribing to the request.

Answer №2

When you see the message console.log('getNotes()', this.notes); before the getData function is called, it means that the API results haven't been fetched yet. This is why there is no data displayed in the log when the page loads.

Would you mind sharing the code from notes.component.html?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Updating the value of the chosen drop down option upon selection

I currently have a Material UI dropdown menu implemented in my project. My goal is to use the selected option from the drop down menu for future search functionality. How can I utilize onChange() to store the selected option effectively? At the moment, I ...

"Unraveling the layers: Mastering nested API calls in

Is there a more efficient method to accomplish this task of retrieving all users along with their photos: this.authHttp.get(this.ApiUrl+'users') .map(res => res.json()) .subscribe(users => { for (let user of users) { ...

The Angular2 component link imported in the core.module is not functioning properly

Adhering to the guidelines provided in the Angular style guide found at https://angular.io/styleguide#!#04-11, I have created a simple navigation setup. My app.component contains links like <a routerLink="hello">hello</a>, which work perfectly ...

Allowing cross-origin resource sharing (CORS) in .NET Core Web API and Angular 6

Currently, I am facing an issue with my HTTP POST request from Angular 6. The request is successfully hitting the .net core Web API endpoint, but unfortunately, I am not receiving the expected response back in Angular 6. To make matters worse, when checkin ...

Navigating through sections in NextJS-14: Utilizing useRef for seamless scrolling

In the past, I had developed an older portfolio website using Vite React + TS and implemented useRef for scrolling to sections from the Navbar. Now, my goal is to transition this portfolio to NextJS 14. I transferred my old components and style folders in ...

When the text in the mat-expansion-panel header exceeds the available space, it will be truncated

Is there a way to add the CSS text-overflow: ellipsis style to a mat-expansion-panel in order to display collapsible text with 3 dots? I have tried implementing it in the mat-expansion-panel-header, but it doesn't seem to work. Here is an image illust ...

Unit Testing Angular Components with Karma and Jasmine: Exploring Test Scope

After reading various guides on unit testing, I have gained an understanding that in unit testing, the focus is on testing the logic within a component, with children components tested separately. Despite this knowledge, I still find myself uncertain about ...

Error Alert: missing property data in angular 5 type

I attempted to design an interface in interface.ts. The data consists of an array of objects inside the Column. Below is the code for my interface: export class User { result: boolean; messages: string; Column=[]; data=[]; } export class Column { name ...

Ensuring a component is included in a module or nesting a component within a template

Struggling with Angular (not AngularJS) and facing an issue where my template is not referencing components correctly. It seems like the component is not being recognized, either due to incorrect declaration or importing in the right place. I need guidanc ...

No slides are available for display, resulting in the ngx-owl-carousel console message indicating that the carousel will not be re-rendered

I've been attempting to integrate ngx-owl-carousel-o into my Angular 11 application, but I keep encountering the following message in my console: There are no slides to show. As a result, the carousel will not be re-rendered. Unfortunately, nothing ...

I am completely baffled by the meaning of this Typescript error

In my code, there is a button component setup like this: export interface ButtonProps { kind?: 'normal' | 'flat' | 'primary'; negative?: boolean; size?: 'small' | 'big'; spinner?: boolean; ...

Setting the default value for Angular Material's select component (mat-select)

Many inquiries are focused on setting a default value to display in a "Select" control. In this particular case regarding Angular 8 template driven forms, the issue lies in the inability to show the default value in the mat-select when the button is clicke ...

What are the benefits of incorporating component A into component B as a regular practice?

I am considering creating an instance of Component A within Component B, but I'm unsure if this is a best practice in Angular or if it will just cause confusion. Component A: This component generates a modal window asking the user to confirm file de ...

Animation in Angular stops working once the user logs into the system

After creating an animation that triggers when a social login fails, I encountered an issue where it was working in Chrome but not in Safari initially. However, after some time, the animation started working in Safari as well without me making any changes. ...

Angular 14 troubleshooting: Issues with using getRawValue() in IndexOf function

In this scenario, I have a straightforward Person interface defined as: import { FormArray, FormControl, FormGroup } from '@angular/forms'; import { Address } from './address'; export class Person { id: FormControl<number>; n ...

Tips for seamless integration of Django and Angular routing

How can I make the Angular 2 URL work with Django in an Angular 2 app served by Django, even when reloading the page? For example, let's say a Django-served page has the URL http://localhost:8000/home. On this page, there are 3 tabs and one of them c ...

utilize console.log within the <ErrorMessage> element

Typically, this is the way the <ErrorMessage> tag from Formik is utilized: <ErrorMessage name="email" render={(msg) => ( <Text style={styles.errorText}> ...

Adding a unique prefix for Angular2 routes in various environments

Imagine you are working on an Angular2 application in the development phase, and it is currently running smoothly on localhost:3000. All the routes are functioning properly. However, for deployment on myserver.com/myapp/, you need to add a prefix of myapp ...

Error: Attempting to access the property 'cinemaName' of an undefined object

I am brand new to using angular2 and higher. My form definition with an input field of type text looks like this: <form class="form-horizontal" name="form" role="form"> <div class="form-group"> <label class="col-md-3 co ...

The method Office.context.mailbox.item.internetHeaders.setAsync has not been configured

I am integrating the Microsoft Office API into Outlook. I'm attempting to add an extra x-header to my email in the composer scope for later identification. To achieve this, I referred to the following documentation: https://learn.microsoft.com/en-us/j ...