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 {
}
}