ayl*_*yls 39 javascript youtube angular
我的AngularJS 2应用程序有问题(我使用的是AngularJS 2的RC5版本).似乎已清理的URL正在触发更改检测,然后更新div
以下内容,尽管我的组件状态没有任何更改.
从用户的角度来看,这表现为视频在播放时的重新加载.
所以在我的组件视图中我有:
<div *ngIf="isVideo(item)">
<iframe [src]="getTrustedYouTubeUrl(item)" scrolling="no" frameborder="0" allowfullscreen></iframe>
</div>
Run Code Online (Sandbox Code Playgroud)
上面组件代码中函数的实现是:
getTrustedYouTubeUrl(linkedVideo:LinkedVideoModel) {
return this.sanitizer.bypassSecurityTrustResourceUrl(linkedVideo.video.url);
}
Run Code Online (Sandbox Code Playgroud)
在调试器中,我看到div通过AngularJS 2框架中触发的内容经常刷新.
如果我用硬编码的URL替换上面的HTML代码段,问题就会消失:
<div *ngIf="isVideo(item)">
<iframe src="<hardcoded youtube url here>" scrolling="no" frameborder="0" allowfullscreen></iframe>
</div>
Run Code Online (Sandbox Code Playgroud)
所以我怀疑URL清理导致了它.
谁能指出我正确的方向?嵌入式YouTube视频的工作示例可能是哪些网址绑定到组件上的属性?
ayl*_*yls 57
弄清楚了.
对任何感兴趣的人 问题是在我的HTML中使用这个功能
[src]="getTrustedYouTubeUrl(item)"
Run Code Online (Sandbox Code Playgroud)
一旦我在我的服务中加载数据并将iframe绑定更改为此更改代码以计算安全URL,重新加载副作用就消失了
<iframe [src]="item.video.safeUrl" scrolling="no" frameborder="0" allowfullscreen></iframe>
Run Code Online (Sandbox Code Playgroud)
注意thatr我现在绑定到一个属性.
yur*_*zui 25
我会尝试用纯管道
Angular仅在检测到输入值的纯更改时才执行纯管道.纯变化是对原始输入值(String,Number,Boolean,Symbol)的更改或更改的对象引用(Date,Array,Function,Object).
管道可能看起来像(RC.6 - DomSanitizer而不是DomSanitizationService):
@Pipe({ name: 'safe' })
export class SafePipe implements PipeTransform {
constructor(private sanitizer: DomSanitizer) {}
transform(url) {
return this.sanitizer.bypassSecurityTrustResourceUrl(url);
}
}
Run Code Online (Sandbox Code Playgroud)
并使用它如下:
<iframe [src]="url | safe" frameborder="0" allowfullscreen></iframe>
Run Code Online (Sandbox Code Playgroud)
Plunker示例(尝试按下按钮)
结合之前的答案,使其以这种方式工作:
component.ts(仅相关部分)
import { DomSanitizer } from '@angular/platform-browser';
constructor(
private sanitizer: DomSanitizer
) {
this.sanitizer = sanitizer;
}
ngOnInit() {
this.getTrustedUrl('http://someUrl');
}
getTrustedUrl(url:any){
this.safeUrl = this.sanitizer.bypassSecurityTrustResourceUrl(url);
}
Run Code Online (Sandbox Code Playgroud)
template.html
<iframe
[src]='this.safeUrl'>
</iframe>
Run Code Online (Sandbox Code Playgroud)
您可以保留原始解决方案,而仅使用 changeDetection: ChangeDetectionStrategy.OnPush
Run Code Online (Sandbox Code Playgroud)<div *ngIf="isVideo(item)"> <iframe [src]="getTrustedYouTubeUrl(item)" scrolling="no" frameborder="0" allowfullscreen></iframe> </div>
归档时间: |
|
查看次数: |
11073 次 |
最近记录: |