angular - This.sanitizer 在 NgOninit 函数(Angular,TS)之外未定义
问题描述
首先,我将 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
绑定事件流,因此可以通过两种方式添加事件侦听this
器以确保正确:-
箭头功能(内部ngOnInit
):-
primaryWorkspace.addChangeListener((event)=>this.updateURL(event));
.bind
(内部constructor
):-
this.updateURL = this.updateURL.bind(this);
在ngOnInit
:-
primaryWorkspace.addChangeListener(this.updateURL);
另外我认为你的意思是addEventListener('change',...
) 而不是addChangeListener
.
推荐阅读
- python - 如何比较数据框中不同年份的月度值变化,Pandas/Python
- android - 我应该采用哪种格式和字体大小?
- javascript - 为什么我的 Firestore 文档包含对象的名称?
- android - 使用 Gson 和 Volley 删除额外的括号
- python - 从科学格式的文本文件中读取两列并用 Python 绘图
- java - 无法在 Android O 中构建 NotificationCompat.Builder
- javascript - 用不同的变量命名变量
- php - SQL:如何在两个表中使用 REPLACE INTO 并且只有特定值匹配?
- django - 如何在 django-heroku 中部署媒体文件?
- ts-node - 如何将参数传递给 ts-node 处理的脚本