我正在尝试在 typescript 中调用自定义 javascript 警报。问题是我不能在 javascript 中使用“this”关键字, typescript 代码不等待 javascript 函数完成。
我的意思是:
declare var $: any;
declare var swal: any;
...
delete(id: number) {
var toDeleteOrNot: boolean = false;
swal({
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel plx!",
closeOnConfirm: false,
closeOnCancel: false
}, function (isConfirm: boolean) {
if (isConfirm) {
toDeleteOrNot = true;
swal("Deleted!", "Your imaginary file has been deleted.", "success");
} else {
swal("Cancelled", "Your imaginary file is safe :)", "error");
}
});
if (toDeleteOrNot) {
this.getagentiiService.deleteAgentie(id).subscribe(x => {
this.populateAgentii();
});
}
}
同时调用函数(swal) 和“if”。 Var toDeleteOrNot in if 保持其初始化值(在本例中为 false)。我无法在 javascript 中移动“if”,因为它给出了
'this' implicitly has type any because it does not have a type annotation
如何在 typescript 中使用这个自定义 javascript 函数?
最佳答案
您正在使用不允许您使用 this
的 function
关键字。使用箭头函数符号,即 ( ) =>
并将代码更改为以下以在内部使用 this
:
swal({
//......
}, (isConfirm: boolean) => {
if (isConfirm) {
toDeleteOrNot = true;
swal("Deleted!", "Your imaginary file has been deleted.", "success");
} else {
swal("Cancelled", "Your imaginary file is safe :)", "error");
}
if (toDeleteOrNot) {
this.getagentiiService.deleteAgentie(id).subscribe(x => {
this.populateAgentii();
});
}
});
关于javascript - 如何在 typescript 组件中调用 javascript 警报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45939891/