所以问题如下。我用Sweet Alert制作了AlertService。我需要确认用户是否确定要删除然后执行它。我有回调上下文切换的麻烦尽管我使用箭头功能,并尝试bind()。这是代码:
AlertService
/**
* This is a generic confirmation alert.
* @param object the object with properties to be displayed.
* @return {boolean} if confirmed, true, else null.
*
* For e.g. To generate an warning for example pass 'warning' in type attribute.
*/
confirmAlert(object: any, callback: Function): any {
swal({
title: object.title,
text: object.text,
type: object.type,
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'OK'
}).then(function (res) {
swal({
title: object.confirmTitle,
text: object.confirmText,
type: 'success'
});
return callback(true);
}, function (cancel) {
swal({
title: 'Cancelled',
text: 'Action cancelled',
type: 'error'
})
return callback(null);
});
}
UsersComponent
/**
* Deletes the selected user. Displays an alert to confirm.
* Refreshes the current users array that is displayed in a table..
*/
deleteUser() {
let usersToDelete = {
'users': this.users
};
this.alertService.confirmAlert(this.createMessages.alert.delete, (confirm) => {
if (confirm) {
this.webService.delete(environment.routes.users.userUrl, usersToDelete).subscribe(res => {
if (res.status == 200) {
this.alertService.okAlert(this.createMessages.alert.deleteSuccess);
}
});
}
});
this.refreshUsers();
}
问题是包含所选用户的对象永远不会到达webService。我安慰了所有的东西,然后遇到了我不知道如何解决的问题。
答案 0 :(得分:0)
问题是我在回调之外有了refreshUsers()而我没有意识到它正在删除我的 this.users :
/**
* Deletes the selected user. Displays an alert and refreshes the current array.
*/
deleteUser() {
let usersToDelete = {
'users': this.users
};
this.alertService.confirmAlert(this.allMessages.alert.delete, (res) => {
if (res) {
this.webService.delete(environment.routes.users.userUrl, usersToDelete).subscribe(res => {
if (res.status == 200) {
this.refreshUsers();
}
});
}
});
}
/**
* This method is used to refresh the current displayed users table.
* Select a user and it's index.
* Delete it from this.all array.
* Delete it from this.users array.
* Call this.getAllUsers() to refresh the array.
*/
refreshUsers() {
while (this.users.length > 0) {
this.all.forEach(element => {
let i = this.users.indexOf(element._id);
if (i != -1 && this.users.length >= 0) {
let e = this.all.indexOf(element);
this.all.splice(e, 1);
this.users.splice(i, 1);
this.getAllUsers();
}
});
}
}