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

Error message: Unable to access property 'post' from undefined - Angular 2

Here is the snippet of code in my component file: import { Component, Injectable, Inject, OnInit, OnDestroy, EventEmitter, Output } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import & ...

Issue: The use of destructuring props is required by eslint, and I'm currently working with a combination of react and types

I typically work with React in JavaScript, and I recently encountered an error message stating "Must use destructuring props at line 14" while trying to define a button for use in a form. Here is the code snippet in question: import React from 'react& ...

While working with Ngrx/effects, an error with code TS2345 occurred. The error message stated that the argument is of type 'Product[]', which cannot be assigned to a parameter of type

When I compile my code, I encounter the following issue (despite not finding any errors in the browser console and the application functioning properly). An error occurs in src/app/services/product.service.ts(15,9): The type 'Observable<Product> ...

Issue with recognizing global methods in Vue and Typescript – help needed

I have a Vue mixin that looks like this: const languageMixin = Vue.extend({ methods: { $getLanguages: function(): object { return { en: 'english' } } } } Vue.mixin(languageMixin) ...

Expanding mat-sidenav by clicking a button located outside of mat-sidenav-container

I attempted to replicate the mobile-friendly design seen in the Angular Material teams' example found on this link. Here is how I structured my component: <app-component-0></app-component-0> <div class="d-lg-none"> <button ...

Having trouble launching my node application on port 80 on Ubuntu 16.04

Trying to run my node app on port 80 in Ubuntu 16.04 is proving to be a challenge. Despite the fact that the port is not in use, when attempting to start my app with npm start, an error message stating "Port already in use" is displayed. According to infor ...

How can I configure a mocked dependency in Jest to return a specific value in a function?

I am currently working on simulating a mongoose model to facilitate unit testing for an express controller. To keep things simple, I've removed all unnecessary code and provided below the specific scenario I'm dealing with. Here's the snippe ...

Explore the potential of utilizing Reactive Forms in conjunction with storybook templates

Currently, I am working on developing some custom components and form elements that I intend to include in Storybook. To ensure completeness, I want the stories to utilize FormControl and FormGroup to demonstrate a real-world use case. Here is an example ...

Issue encountered with passport-local in TypeScript: Unable to utilize 'new' with an expression that does not have a call or construct signature

Currently, I am attempting to implement the passport-local package in TypeScript (version 2.0.0RC); however, a compiler error has arisen: Error TS2351: It is not possible to use 'new' with an expression lacking a call or construct signature. ...

Ionic4: Troubleshooting the playback of audio files on a web-based application

Currently, my project involves using Ionic 4 in combination with Angular. I am facing a challenge where I need to play an audio file (mp3/wav) when an image is clicked. Despite working on this for a week, I have been unable to figure it out. Can anyone pr ...

Is there a specific type in typescript that represents every iterable object?

We have a unique function shown below: export const transformUndefinedToNull = (obj) => { const convert = (o) => { Object.keys(o).forEach((key) => { const value = o[key]; if (value === undefined) { o[key] = null; } ...

Tips for setting unique base_url for separate environment instances in angular2

My index.html file in Angular2 has the following content: When I build it in default mode (development mode) using npm run build, I want it to have: <base href="/"> However, when I build it in production mode (npm run build --target=production), I ...

Converting an array of objects into a string list, separated by commas: a step-by-step guide

Looking to restructure an array in Angular. Here's an example of the current array: 0: "Car 1" 1: "Car 2" 2: "Car 3" 3: "Car 4" 4: "Car 5" 5: "Car 6" The goal is to transform it into Car1,Ca ...

Setting up pagination in Angular Material can sometimes present challenges

After implementing pagination and following the guidelines provided here. This is my code from the app.component.ts file - import { Component, OnInit, ViewChild } from '@angular/core'; import {MatPaginator} from '@angular/material/paginat ...

Which is better for storing a collection of Components in a Service: Array or QueryList?

I have developed a PopupService with the following structure: export class PopupService { popups: PopupComponent[] = []; open(popup: PopupComponent) { this.popups.forEach(popup => popup.active = false); popup.active = true; } close(p ...

Updating the old version of an Angular app on Azure using VS Code can be challenging as the deployment process may not automatically replace

After making changes to my Angular App and testing it locally with 'ng serve', I used 'ng build' to generate artifacts in the 'dist' directory. Utilizing the Azure App Services extension in VS code, I selected the 'dist&a ...

Creating a dynamic 3D bar chart within an Angular 8 application is possible through the utilization of powerful visualization libraries such as d3

Currently, I am attempting to develop a 3D bar chart within an Angular 8 application. Despite consulting the documentation for d3.js, three.js, and plotly chart frameworks, I have been unable to find any sample code. I kindly request if anyone could share ...

Rendering a component in React based on multiple conditions

Checking sessionStorage and another state variable before rendering a component is essential for my application. I want to avoid showing the same message multiple times within the same session. This is how I have implemented it: const addSession = (noteId: ...

Ways to display all current users on a single page within an application

I have come across a project requirement where I need to display the number of active users on each page. I am considering various approaches but unsure of the best practice in these scenarios. Here are a few options I am considering: 1. Using SignalR 2. ...

Exploring how to set dropdown menu width for Angular2 mat-select options

Currently, I am using the angular2 mat-select control and facing an issue with the width and position of its dropdown list menu. By default, it is wider and overflows the element on both sides by a few pixels. I have not found any option for adjusting the ...