First, I imported DomSanitizer to the component:
import { DomSanitizer, SafeResourceUrl} from '@angular/platform-browser';
After that, I created a class and added it to the constructor:
export class BlocklyComponent implements OnInit {
primaryWorkspace: Blockly.WorkspaceSvg;
GEE = "PCFET0NUWVBFIGh0bWw+Cgo8aGVhZD4KPG1ldGEgY29udGVudD0idGV4dC9odG1sOyBjaGFyc...";
public geeMap: SafeResourceUrl;
constructor(private sanitizer: DomSanitizer) {}
ngOnInit() {
Inside the NgOnInit function it works correctly, however, in the updateURL function (outside NgOnInit but inside the class) it says that this.sanitizer is undefined:
//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}`);
}
I know that this is a typical problem that has happened to me many times, however now I don't know how to solve it. I have tried to look for the undefined problem in different forums but I still couldn't be able to solve it. Thank you very much
Since you're going out of the Angular
flow of binding events, you can add the event listener in two ways to take care of the correct this
:-
Arrow functions (inside ngOnInit
) :-
primaryWorkspace.addChangeListener((event)=>this.updateURL(event));
.bind
(inside constructor
) :-
this.updateURL = this.updateURL.bind(this);
And in ngOnInit
:-
primaryWorkspace.addChangeListener(this.updateURL);
Also I think you meant addEventListener('change',...
) instead of addChangeListener
.