我正在尝试使用angular4开发一个简单的联系人列表应用程序 我想在点击确认按钮后删除联系人,在删除方法上,它为那里的联系人提供了未定义的函数。
export class HomeComponent implements OnInit {
contacts: Array<any>;
// Create an instance of the DataService through dependency injection
constructor(private _dataService: DataService) {
// Access the Data Service's getUsers() method we defined
this._dataService.getContacts()
.subscribe(res => {console.log(res);
this.contacts=res;
});
}
ngOnInit() {
var contact={"firstname":"jishnu","lastname":"koottala","email":"jishnu45@gmail.com","mobile":"7890678970"};
var appstest = new Array();
appstest.push({"firstname":"Jishnu","lastname":"koottala","emailid":"jishnu45@gmail.com","mobile":"7890678970"});
appstest.push({"firstname":"Luvish","lastname":"yadav","emailid":"luvishyadav@gmail.com","mobile":"787447970"});
appstest.push({"firstname":"Mohan","lastname":"singh","emailid":"mohan.singh3@gmail.com","mobile":"78906576770"});
appstest.push({"firstname":"Anurag","lastname":"dwivedi","emailid":"anurag.dwivedi@gmail.com","mobile":"78975778970"});
// this.contacts=appstest;
}
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 () {
//this._dataService.deleteContact(id);
var cts = this.contacts;
this.taskService.deleteContact(id).subscribe(data => {
if(data.n == 1){
var cts = this.contacts; //i have to use 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'
);
})
}
}
&#13;
答案 0 :(得分:0)
您应该使用箭头函数而不是常规函数,以便从声明的上下文中捕获它。
答案 1 :(得分:0)
const self=this;
swal({}).then(function(){
//You can access self here
});
否则将此保留在其他变量
中{{1}}