首页 > 解决方案 > 属性 '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”方法。给我一个解决方案。

标签: angularangular5

解决方案


问题

您正在使用嵌套的匿名函数,这就是为什么上下文已更改并且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"
        });
      }
    };

推荐阅读