基本上,我的component.ts文件中有一个称为“ addToast”的方法。这是:-
addToast(options): any {
if (options.closeOther) {
this.toastyService.clearAll();
}
this.position = options.position ? options.position : this.position;
const toastOptions: ToastOptions = {
title: options.title,
msg: options.msg,
showClose: options.showClose,
timeout: options.timeout,
theme: options.theme,
onAdd: (toast: ToastData) => {
/* added */
},
onRemove: (toast: ToastData) => {
/* removed */
}
};
switch (options.type) {
case "default":
this.toastyService.default(toastOptions);
break;
case "info":
this.toastyService.info(toastOptions);
break;
case "success":
this.toastyService.success(toastOptions);
break;
case "wait":
this.toastyService.wait(toastOptions);
break;
case "error":
this.toastyService.error(toastOptions);
break;
case "warning":
this.toastyService.warning(toastOptions);
break;
}
}
Run Code Online (Sandbox Code Playgroud)
并且我尝试将此方法用于另一个称为“ onLoadFile”的方法。这是:-
onLoadFile(event) {
var img = new Image();
img.src = event.target.result;
var isUploadPic = null;
img.onload = function(): any {
console.log(img.width, "x", img.height);
// var isUploaded = false;
if (img.width != 600 && img.height != 600) {
this.addToast({
title: "FAIL!",
msg: "Diamension Should Be 600x600.",
timeout: 6000,
theme: "default",
position: "top-right",
type: "error"
});
}
};
console.log(isUploadPic);
}
Run Code Online (Sandbox Code Playgroud)
但它向我显示了VSCODE上的错误,即“类型'GlobalEventHandlers'上不存在属性'addToast'”。我正在分享一个形象。
并且我正在共享控制台错误的图像。在下面。
请告诉我如何在该位置使用“ addToast”方法。给我一个解决方案。
Sun*_*ngh 11
您正在使用嵌套的匿名函数,这就是为什么上下文已更改并且this指向GlobalEventHandlers非Component类的原因。
您有两种方法可以解决此问题
修复1
保留引用this并在匿名函数内使用的第一个修补程序。可以将当前上下文(this)分配给某些变量say,self并且可以在深层嵌套函数中的任何位置使用它。this可能会更改,但self始终指向父级。
let self = this;
img.onload = function(): any {
console.log(img.width, "x", img.height);
// var isUploaded = false;
if (img.width != 600 && img.height != 600) {
self.addToast({
title: "FAIL!",
msg: "Diamension Should Be 600x600.",
timeout: 6000,
theme: "default",
position: "top-right",
type: "error"
});
}
};
Run Code Online (Sandbox Code Playgroud)
修复2
第二种选择是使用箭头功能。在箭头函数中,this始终指向调用它的上下文。这是比修复1更好的方法。
img.onload = () => {
console.log(img.width, "x", img.height);
// var isUploaded = false;
if (img.width != 600 && img.height != 600) {
this.addToast({
title: "FAIL!",
msg: "Diamension Should Be 600x600.",
timeout: 6000,
theme: "default",
position: "top-right",
type: "error"
});
}
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2480 次 |
| 最近记录: |