Looking for a simple way to work with arrays, I decided to create this custom extension class:
export class ArrayType<T extends IEntity> extends Array<T> {
add(item: T) {
this.push(item);
}
remove(item: T) {
console.log(item);
const index = this.findIndex(x => x.id === item.id);
this.splice(index, 1);
}
update(item: T) {
const index = this.findIndex(x => x.id === item.id);
this.splice(index, 1, item);
}
}
export interface IEntity {
id: number;
}
After creating the methods, I attempted to utilize them in my Angular application as follows:
export class DepartmentListComponent implements OnInit {
constructor(public service: DepartmentService) { }
items: ArrayType<Department>;
ngOnInit() {
this.service.getAll().subscribe(x => this.items = x);
}
onDelete(item: Department) {
this.items.remove(item);
this.service.delete(item.id);
}
onUpdate(item: Department) {
this.items.update(item);
this.service.update(item.id, item);
}
onAdd(item: Department) {
const id = this.service.add(item);
item.id = id;
this.items.add(item);
}
}
However, I encountered a runtime error displayed at https://i.sstatic.net/VZqbn.png.
Being relatively new to TypeScript/JavaScript and Angular, I am seeking assistance in resolving this issue.
If you have any suggestions or tips on how to fix this problem, please share them. Your input is greatly appreciated!