Reputation: 512
I want to remove a specific object from a list. The object model looks like this:
export class Task {
taskId: number;
projectId: Project;
userId: User;
state: string;
description: string;
}
I created a list of Task objects and I want to delete a Task that has a specific taskId.
moveTaskInProgress(task: Task) {
console.log('The task is in progress...');
task.state = 'IN_PROGRESS';
this.taskService.updateTask(task).subscribe((nbOfUpdates) => {
console.log('Number of updates: ' + JSON.stringify(nbOfUpdates));
this.removeItemFromAListOfTasks(task, this.openTasks);
console.log('List of task task: ' + JSON.stringify(this.openTasks));
});
}
removeItemFromAListOfTasks(task: Task, listOfTasks: Task[]) {
let filteredList: Task[];
filteredList = listOfTasks.filter(item => item.taskId !== task.taskId);
}
I have a method that receive a task, call a method that updates some properties, and after that i want to delete the task from the list.
But it seems that nothing happen. Could you, please, help me with this?
Upvotes: 1
Views: 3982
Reputation: 13515
Filtering an array returns a new array with a subset of the original items. It does not modify the original array.
Instead you need to splice it.
moveTaskInProgress(task: Task) {
console.log('The task is in progress...');
task.state = 'IN_PROGRESS';
this.taskService.updateTask(task).subscribe((nbOfUpdates) => {
console.log('Number of updates: ' + JSON.stringify(nbOfUpdates));
this.removeItemFromAListOfTasks(task, this.openTasks);
console.log('List of task task: ' + JSON.stringify(this.openTasks));
});
}
removeItemFromAListOfTasks(task: Task, listOfTasks: Task[]) {
const index = listOfTasks.indexOf(task);
if (index === -1) {
// the task doesn't exist in the array, no need to continue
return;
}
// delete 1 item starting at the given index
listOfTasks.splice(index, 1);
}
This is assuming that the task originated from the array. Otherwise you will need to find the index:
const index = listOfTasks.findIndex(x => x.taskId === task.taskId);
Upvotes: 3
Reputation: 31105
You could send only the ID instead of sending the complete object.
removeItemFromAListOfTasks(id: any, listOfTasks: Task[]) {
return listOfTasks.filter(tast => task.taskId !== id);
}
Now it can be called like
this.openTasks = this.removeItemFromAListOfTasks(task.taskId, this.openTasks);
Upvotes: 0
Reputation: 1
there is spelling mistake use tasks.tasskId instead of task.
tasks: Task[]; // here I received some objects from a HTTP request.
filteredList: Task[];
filteredList = listOfTasks.filter(item => item.taskId !== tasks.taskId);
Upvotes: -1