angular - 属性 'addToast' 在类型 'GlobalEventHandlers' 角度 5 上不存在
问题描述
基本上我的 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;
}
}
我正在尝试将此方法用于另一种称为“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);
}
但它在 VSCODE 上向我显示了一个错误,即“属性 'addToast' 在类型 'GlobalEventHandlers' 上不存在”。我正在分享一张图片。
而且我正在分享控制台错误的图像。这是下面。
请告诉我如何在该位置使用“addToast”方法。给我一个解决方案。
解决方案
问题
您正在使用嵌套的匿名函数,这就是为什么上下文已更改并且this
指向GlobalEventHandlers
不是 Component 类的原因。
使固定
您有两种选择来解决此问题
修复 1
第一个修复保留引用this
并在匿名函数中使用它。当前上下文 ( this
) 可以分配给某个变量 sayself
并且可以在深度嵌套函数中的任何地方使用。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"
});
}
};
修复 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"
});
}
};
推荐阅读
- perl - Perlbrew 没有列出已安装的 Perl 版本
- vuetify.js - 如何更改 Vuetify 中数据表的背景颜色?
- python - 无服务器 python 无法导入模块处理程序,并且可能无法使用 sls deploy 正确 dockerizing
- python - 将输入字符串张量转换为 python 字符串
- wordpress - Wordpress URL 重写问题
- git - Git - 撤消合并更改并重做合并
- python - 使用python通过RPW访问元素的参数值
- git - 基于消息的壁球提交
- css - 选择选项时,项目符号出现在多选下拉框下方
- php - 如何使 require_once 路径动态化?