问题描述
我创建了一个组件,该组件应该根据在输入中传递给它的属性显示视频...如果我插入静态数据,它对我有用,但是开关不行!
export class VideoComponent implements OnInit {
@input() currentVideo: string | undefined;
url: any;
video: any = { id: 'yOYmdyaSocg' };
baseUrl: string = 'https://www.youtube.com/embed/';
constructor(
private sanitizer: DomSanitizer,) {
switch (this.currentVideo) {
case 'foo':
this.video.id = 'yOYSOCsdsdg';
break;
case 'bar':
this.video.id = '3Z4J_bddKE';
break;
case 'foo2':
this.video.id = 'a8dpnc64';
break;
case "bar2":
this.video.id = 'HZySqmdsclEuSQ';
break;
default:
this.video.id = 'TYYW_WsdwYHuM';
}
this.url = this.sanitizer.bypassSecurityTrustResourceUrl(
this.baseUrl + this.video.id
);
}
}
I followed this guide to create it and it works for me,but the switch
doesn't work for me.
解决方法
从您的代码看起来,您似乎正在实现 OnInit 接口,但尚未添加 ngOnInit 方法。最好添加 ngOnInit 方法,然后根据其中的输入绑定做出决定,而不是在构造函数中。这是因为 OnInit 生命周期钩子只有在所有输入绑定都被解析后才会被调用。看看这里就知道区别了:Difference between Constructor and ngOnInit。静态数据之所以起作用,是因为它就像使用一些已经可用的字符串值设置字段一样,而输入绑定显然不是这种情况,因为它们尚未在构造函数中解析。
因此,您需要做的就是将 Constructor 中存在的代码移动到 ngOnInit 方法,并让 sanitizer 保持在构造函数参数中的状态。依赖注入器将确保 DOMSanitizer 被注入。应该就是这样。