我正在尝试删除我的angular cli应用中的项目。我已经使用甜蜜警报作为警报,我想从列表中删除一个项目。这是一个代码。此代码位于typescript文件中。
import { AuthenticationService } from '../../../services/authentication.service';
declare var swal: any;
export class AdminUsersComponent implements OnInit {
constructor(
private authService: AuthenticationService,
) { }
deleteUser(id) {
let userData = {
user_id: id
};
swal({
title: "Are you sure?",
text: "You will not be able to recover this!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
closeOnConfirm: false
}, function(){
this.authService.deleteUser(userData).subscribe(data => {
// response
});
});
}
}
问题是当我确认删除时,它给出了错误,“this.authserivce”未定义。如果我不使用甜蜜警报作为确认,它正常工作。我猜我需要在回调函数中传递参数但不知道我应该传递什么。那我怎么解决这个问题呢?
答案 0 :(得分:2)
第一个解决方案:使用arrow function,因为函数表达式绑定this
并使用自己的this
swal({
title: "Are you sure?",
text: "You will not be able to recover this!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
closeOnConfirm: false
}).then((result) => {
if (result.value) {
this.authService.deleteUser(userData).subscribe(data => {
// response
});
}
});
第二个解决方案:
let that = this;
swal({
title: "Are you sure?",
text: "You will not be able to recover this!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
closeOnConfirm: false
}).then(function(result) {
if (result.value) {
that.authService.deleteUser(userData).subscribe(data => {
// response
});
}
});