Angular: Unable to load todo list when filtering results

I am currently developing a simple todo application using Angular. I have encountered an issue where filtering results from an array imported from services does not happen in real-time. The filtering only works when I navigate to another page (since it's a single-page application) and then return to the todo list. If I remove the filter part from the constructor, the list is displayed correctly.

todos.service.ts

import { Todo } from "./models/todo";

export let arrayTodos: Todo[] = [
  {
    id: 34875487532,
    title: 'prova1',
    completed: true
  },
  {
    id: 545463,
    title: 'prova2',
    completed: false
  }
];

let id: number = 0;

export function getTodos(): Promise<Todo[]> {
  return new Promise((success, error) => {
    setTimeout(() => {
      success(arrayTodos);
    }, 2000);
  });
}

export function aggiungiTodo(title: string) {
  return new Promise<void>((success, error) => {
    setTimeout(() => {
      id++;
      let newTodo: Todo = {
        id: id,
        title: title,
        completed: false
      };
      //arrayTodos = [...arrayTodos, newTodo];
      arrayTodos.push(newTodo);
      //console.log(arrayTodos);
      success();
    }, 2000);
  });
}

todo.page.ts

import { Component, OnInit } from '@angular/core';
import { Todo } from './models/todo';
import * as TodoService from './todos.service';

@Component({
  template: `
    <div class="input-area">
      <input placeholder="inserisci una task" type="text" (keyup)="getTesto($event)">
      <button class="addTask" type="button" (click)="addTodo()">+</button>
      <ul>
        <li *ngFor="let todo of todos">{{todo.title}}</li>
      </ul>
    </div>
  `,
  styles: []
})
export class TodoPage implements OnInit {
  todos!: Todo[];
  titoloNuovoTodo!: string;

  constructor() {
    /* TodoService.getTodos().then((res: Todo[])=>this.todos = res.filter(todo => !todo.completed)); */
    TodoService.getTodos().then((res: Todo[]) => {
      this.todos = res.filter(todo => !todo.completed);
    });
  }

  getTesto(event: Event): void {
    const target = <HTMLInputElement>event.target;
    this.titoloNuovoTodo = target.value;
  }

  addTodo() {
    console.log(this.todos);

    TodoService.aggiungiTodo(this.titoloNuovoTodo);
  }

  ngOnInit(): void {
  }
}

Answer â„–1

When using Angular, it is best practice to initialize data in the ngOnInit lifecycle hook instead of the constructor. This approach ensures proper execution and avoids potential issues.

Additionally, I highly recommend utilizing Observables over Promises for better data handling. You can easily convert a Promise into an Observable using the from operator. Remember to use the async pipe in your template when displaying Todos for seamless updates.

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

A Guide to Iterating Through Arrays of Objects Using TypeScript

Currently, I am engrossed in an Angular project where I am fetching an object containing an array of objects from an API. The object being passed to the API as a parameter through my service is called "reportData". Here is an example of the data retrieve ...

The fuse box was to blame for triggering a GET request to http://localhost:4444/, resulting in the error message

I encountered an issue with fuse-box and P5.js where I received a GET http://localhost:4444/ net::ERR_CONNECTION_REFUSED. The complete code can be accessed on GitHub. The fuse.js file contains the following configuration: const { FuseBox, WebIndexPlugin ...

Tips for passing a false boolean state value back to the parent component in ReactJS

parent.tsx const [modal, setModal] = useState(false); const [detail, setDetail] = useState({}); <confirmation state={setModal(true)} data={detail} /> confirmation return ( <SweetAlert show={state} success title="Confirm ...

Tips for troubleshooting JSON sorting in Angular

I am currently troubleshooting column positions within my application and need to inspect the sorted column definition. After retrieving the column definition from my API, I proceed to sort them. However, I also want to log the sorted list/Array to my co ...

The filter pipe in Angular 7 is not functioning properly

Upon page loading and API call initiation, I am encountering an issue with the ngFor loop not displaying all the values. However, when I manually input a search query in the search box for filtering, the functionality works flawlessly. My goal is for all v ...

NgClass: checking if the array includes the specific item

I'm attempting to apply a class if an item exists within the array, but I'm struggling with it. <div *ngFor="let item of someList"> <button [ngClass]="{'isSelected': selectedArr includes item}"></button> ...

Using the setupFiles option to set up files and execute code prior to running tests

I need to ensure that some code is executed before all tests are run. My jest.config.js setup: // truncated... setupFilesAfterEnv: [ "./jest.setup.ts" ] The content of jest.setup.ts: async function setUp() { const first = new Prom ...

What is the best way to perform a conditional check and return a customized object while working with a Promise?

I have developed a provider specifically for handling all Firebase database related requests. In the getUser method, when the data is fetched from the database using .once which returns a promise, if the object is null it currently returns null. This means ...

Issue with PassportJS and Express 4 failing to properly store cookies/session data

I have a situation with my Express 4 app using Passport 0.3.2. I've set up a passport-local strategy, and it's successfully retrieving the user information when the /session endpoint is provided with a username and password. The issue arises whe ...

Error message "The result of this line of code is [object Object] when

Recently, I encountered an issue while retrieving an object named userInfo from localStorage in my Angular application. Despite successfully storing the data with localStorage.setItem(), I faced a problem when attempting to retrieve it using localStorage.g ...

A guide on implementing TypeScript generics constraints when using the useState hook

Currently, I am delving into Typescript and have developed a custom React hook that resembles the following structure: import { useEffect, useState } from 'react'; type TypeOne = { one: string; }; type TypeTwo = { two: number; }; type TypeTh ...

Tips for simulating mouse events in Jasmine tests for Angular 2 or 4

New to Jasmine testing, I'm exploring how to test a directive that handles mouse events such as mouse down, up, and move. My main query is regarding passing mouse coordinates from the Jasmine spec to my directive in order to simulate the mouse events ...

Function editing error

Attempting to retrieve user data for editing in the form is causing an error related to the line where the data is being assigned: **** this.user = data This is the content of edit-user.component.ts: import { Component, OnInit } from '@angular/core ...

Creating accurate JSON data using p-dropdown PrimeNG

I recently started learning Angular and encountered a situation while using the Java API: In my Release class, the category is not required (class Category). @Entity @Table(name = "release") public class Release { @Id @GeneratedValue(strategy = G ...

What is the best way to transfer a @ContentChild attribute to a fairy tale?

Is there a way to transfer an attribute from a component with a @ContentChild decorator to a story? Below is the code for the container component: @Component({ selector: 'app-header', templateUrl: './header.component.html', style ...

Guide on printing in an Ionic application using print.js without the need to open the printer setup page

Our team is currently working on an Ionic web application that utilizes printer functionality. To enable printing, we have integrated the Print.js npm package. However, when we initiate the print method, a setup page displaying details such as printer na ...

Encountering difficulties accessing private variables within the template/html in Angular 5

After creating multiple variables and accessing them in their respective templates or HTML files, I've realized that having all variables set as public can be problematic. I want to convert these public variables to private, but when I do so, I receiv ...

What is the proper way to create a generic class that can produce various output types while implementing a basic interface?

An abstract class is being created here to transform one type of object into another, with a simple interface comprising id:string and type:string. The intention behind the class definition is to emphasize that it will produce an assembly and during insta ...

Difficulty in both passing a value and accessing a child component

I am currently working on a form that includes various elements such as Company, Contact, and Date. Additionally, there is a custom component, a date picker, that is included in the form. When I fill out all the values in the form and submit it, I am able ...

TypeScript modules located within the node_modules directory and then deployed within the wwwroot folder

Implementing this in an ASP.NET Core 2.x web application should have been straightforward considering it's a standard pattern. However, I seem to be doing something very wrong. Here is the folder structure that I am working with: projectRoot ├─â ...