Trying to develop a simple contact list app using Angular 4 and facing an issue with the delete functionality. When attempting to delete a contact, the contacts variable inside the 'then' function is returning undefined.
- The main problem lies within the confirmDel() method
- The goal is to display an alert asking the user to confirm the deletion of a contact
- Once confirmed, the specific contact should be deleted from the component
export class HomeComponent implements OnInit {
contacts: Array<any>;
// Initializing DataService through dependency injection
constructor(private _dataService: DataService) {
this._dataService.getContacts()
.subscribe(res => { console.log(res);
this.contacts = res;
});
}
ngOnInit() {
// Sample contact data
var contact={"firstname":"jishnu","lastname":"koottala","email":"example@email.com","mobile":"7890678970"};
var appstest = new Array();
appstest.push({"firstname":"Jishnu","lastname":"Koottala","emailid":"example1@email.com","mobile":"7890678970"});
...
}
confirmDel(id){
console.log('id is = '+id);
swal({
title: 'Are you sure want to delete this contact?',
text: "You won't be able to revert this!",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
}).then(function () {
var cts = this.contacts;
this.taskService.deleteContact(id).subscribe(data => {
if(data.n == 1){
var cts = this.contacts;
for(var i = 0;i < cts.length;i++){
if(cts[i]._id == id){
cts.splice(i, 1);
}
}
}
});
swal(
'Deleted!',
'Your file has been deleted.',
'success'
);
})
}
}