This.sanitizer 在 NgOninit 函数外未定义 (Angular, TS)

This.sanitizer is undefined outside NgOninit function (Angular, TS)

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

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

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

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

在 NgOnInit 函数内部它工作正常,但是,在 updateURL 函数中(在 NgOnInit 外部但在 class 内部)它说 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 绑定事件流,您可以通过两种方式添加 事件侦听器 以处理正确的 this :-

箭头函数(在ngOnInit内):-

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

.bind(在 constructor 内):-

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

并且在 ngOnInit 中:-

primaryWorkspace.addChangeListener(this.updateURL);

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