Property 'addToast' does not exist on type 'GlobalEventHandlers' angular 5 [duplicate]

自作多情 提交于 2019-12-06 11:34:06

Issue

You are using nested anonymous function and that is why context has been changed and this is point to GlobalEventHandlers not the Component class.

Fix

You have two options to fix this issue

Fix 1

The first fix to keep the reference of this and use it inside the anonymous function. The current context (this) can be assigned to some variable say self and can be used anywhere in deep nested functions. this may change however self will always point to the parent.

   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"
            });
          }
        };

Fix 2

The second option is to use arrow function. In arrow function this always point to the context it is called from. This is better approach than fix 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"
        });
      }
    };
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!