切换到观看 youtube 视频不起作用
switch to view youtube video does not work
我创建了一个组件,该组件应根据输入中传递给它的属性显示视频...如果我插入静态数据,它对我有用,但使用 开关不!
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
);
}
}
从您的代码来看,您似乎正在实现 OnInit 接口,但没有添加 ngOnInit 方法。最好添加 ngOnInit 方法,然后根据那里的输入绑定而不是在构造函数中做出决定。这是因为仅在解析所有输入绑定后才调用 OnInit 生命周期挂钩。看看这里了解区别:。静态数据之所以起作用,是因为它就像用一些已经可用的字符串值设置一个字段,而输入绑定显然不是这种情况,因为它们尚未在构造函数中解析。
因此,您需要做的只是将 Constructor 中的代码移至 ngOnInit 方法,并让消毒剂保持在构造函数参数中的状态。依赖注入器将确保 DOMSanitizer 得到 injected.And 应该是它。
我创建了一个组件,该组件应根据输入中传递给它的属性显示视频...如果我插入静态数据,它对我有用,但使用 开关不!
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
);
}
}
从您的代码来看,您似乎正在实现 OnInit 接口,但没有添加 ngOnInit 方法。最好添加 ngOnInit 方法,然后根据那里的输入绑定而不是在构造函数中做出决定。这是因为仅在解析所有输入绑定后才调用 OnInit 生命周期挂钩。看看这里了解区别:
因此,您需要做的只是将 Constructor 中的代码移至 ngOnInit 方法,并让消毒剂保持在构造函数参数中的状态。依赖注入器将确保 DOMSanitizer 得到 injected.And 应该是它。