export class ClassName implements OnInit {
url: string = "{{'content.url' | translate}}";
urlSafe: SafeResourceUrl;
constructor(public sanitizer: DomSanitizer, private translate: TranslateService) { }
ngOnInit() {
this.translate.stream('content.url').subscribe((text: string) => {
this.urlSafe = this.sanitizer.bypassSecurityTrustResourceUrl(text);
console.log(this.urlSafe);//logs the SafeResourceUrl Object
this.DoAThing();
});
}
DoAThing() {
console.log(this.urlSafe); //undefined
}
}
为什么在这个类中,在ngOnInit
中,我可以记录SafeResouorceUrl
对象
但我一辈子都无法想出如何用下面的方法访问该对象的URL。
granted DoAThing代码可以在ngOnInit中运行,但我需要以这种方式运行它是有原因的,我不知道为什么我会得到未定义。
我在这节课上做错了什么?Angular新手,感谢您的支持!
您可以这样写&它会记录您的值,但您的代码也应该工作。
export class ClassName implements OnInit {
url: string = "{{'content.url' | translate}}";
urlSafe: SafeResourceUrl;
constructor(public sanitizer: DomSanitizer, private translate: TranslateService) { }
ngOnInit() {
this.translate.stream('content.url').subscribe((text: string) => {
this.DoAThing(text);
});
}
DoAThing(url) {
this.urlSafe = this.sanitizer.bypassSecurityTrustResourceUrl(url);
console.log(this.urlSafe);//logs the SafeResourceUrl Object
}
}
您的函数:
DoAThing() {
console.log(this.urlSafe); //undefined
}
未绑定到this
。因此,要调用它,必须使用someSafeResourceUrl.DoAThing
。
或者使用箭头功能:
DoAThing = () => {
console.log(this.urlSafe); // this will always be bound
}
更多
TypeScript中的this