【问题标题】:This.sanitizer is undefined outside NgOninit function (Angular, TS)This.sanitizer 在 NgOninit 函数(Angular,TS)之外未定义
【发布时间】:2021-06-07 06:35:33
【问题描述】:

首先,我将 DomSanitizer 导入到组件中:

import { DomSanitizer, SafeResourceUrl} from '@angular/platform-browser';

之后,我创建了一个类并将其添加到构造函数中:

 export class BlocklyComponent implements OnInit {
      primaryWorkspace: Blockly.WorkspaceSvg;
      GEE = "PCFET0NUWVBFIGh0bWw+Cgo8aGVhZD4KPG1ldGEgY29udGVudD0idGV4dC9odG1sOyBjaGFyc...";
    public geeMap: SafeResourceUrl;
      constructor(private sanitizer: DomSanitizer) {}
ngOnInit() {

在 NgOnInit 函数内部它可以正常工作,但是在 updateURL 函数中(在 NgOnInit 外部但在类内部)它说 this.sanitizer 是未定义的:

//Creates de src that has to be in the iframe. What I need to do is to update this safeResourceUrl.
        this.geeMap = this.sanitizer.bypassSecurityTrustResourceUrl(`data:text/html;base64,${this.GEE}`);

        //Reads the events in a workspace. When it notices a change, it triggers the updateURL function

        primaryWorkspace.addChangeListener(this.updateURL);

      }
      updateURL(primaryEvent) 
         {
          if (primaryEvent.isUiEvent) {
            return; //Do not clone ui events 
          };
          console.log('hola');
         //Problem. Here it sais that this.sanitizer is undefined.
          this.geeMap = this.sanitizer.bypassSecurityTrustResourceUrl(`data:text/html;base64,${this.GEE}`);
        }

我知道这是我经常遇到的典型问题,但是现在我不知道如何解决它。我试图在不同的论坛中寻找未定义的问题,但我仍然无法解决它。非常感谢

【问题讨论】:

    标签: angular typescript ionic-framework sanitizer


    【解决方案1】:

    由于您要退出 Angular 绑定事件流,您可以通过两种方式添加 事件监听器 来处理正确的 this :-

    箭头函数(ngOnInit 内):-

    primaryWorkspace.addChangeListener((event)=>this.updateURL(event));

    .bind(在constructor内):-

    this.updateURL = this.updateURL.bind(this);

    在ngOnInit :-

    primaryWorkspace.addChangeListener(this.updateURL);

    另外我认为你的意思是addEventListener('change',...) 而不是addChangeListener。

    【讨论】:

    • 非常感谢 Lakshya。第二个选项对我很有效。我与这个错误进行了真正的斗争,你已经解决了它。关于你告诉我的 addEventListener,我写不出来,因为我使用的是 Blockly 库,并且需要使用 addChangeListener 读取事件。再次感谢您
    猜你喜欢
    • 2018-01-14
    • 1970-01-01
    • 2017-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-28
    • 1970-01-01
    相关资源
    最近更新 更多