角度安全管道实现,以绕过DomSanitizer剥离内容



我正在使用Angular 9通过youtube api加载一些电影。

我必须创建一个pip,让我的链接能够在html 中工作

这是管道代码

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml, SafeScript, SafeStyle, SafeUrl, SafeResourceUrl } from '@angular/platform-browser';
@Pipe({
name: 'youtube',
})
export class YoutubePipe implements PipeTransform {
constructor(public sanitizer: DomSanitizer) {}
transform(value: any, type: string): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl {
switch (type) {
case 'html':
return this.sanitizer.bypassSecurityTrustHtml(value);
case 'style':
return this.sanitizer.bypassSecurityTrustStyle(value);
case 'script':
return this.sanitizer.bypassSecurityTrustScript(value);
case 'url':
return this.sanitizer.bypassSecurityTrustUrl(value);
case 'resourceUrl':
return this.sanitizer.bypassSecurityTrustResourceUrl(value);
default:
throw new Error(`Invalid safe type specified: ${type}`);
}
}
}

HTML Tage,我认为问题来自:

<div *ngFor="let video of videos" class="col-xl-3 col-md-6 mb-4">
<div class="card border-0 shadow vh-50">
<a href="https://www.youtube.com/watch?v={{ video.id.videoId }}" target="_blank">
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" [src]="https:  //www.youtube.com/watch?v={{ video.id.videoId  | youtube }}" allowfullscreen>
</iframe>
</div>
</a>
<div class="card-body text-center">
<h5 class="card-title mb-0">
<a href="https://www.youtube.com/watch?v={{ video.id.videoId }}"> {{ video.snippet.title }} </a>
</h5>
<div class="card-text text-black-50">{{ video.snippet.title.slice(0, 100) }}</div>
<!-- <p class="card-text">{{ video.snippet.title }}</p> -->
</div>
</div>
</div>

我可以看到控制台中加载的数据,但问题来自iframe标记语法。你能帮我做这个吗。

提前谢谢。

首先,您需要清理整个url,而不仅仅是id,如果您在[ ]s中进行数据绑定,则需要这样做:

<iframe [src]="('https://www.youtube.com/watch?v=' + video.id.videoId) | youtube : 'resourceUrl'"></iframe>

CCD_ 2绑定用于插值。比如:

<iframe class="embed-responsive-item" src="{{ 'https://www.youtube.com/watch?v=' + video.id.videoId }}" allowfullscreen>

但它在这里不起作用。当把东西标记为安全时,需要输入绑定。返回值实际上不是一个字符串,而是一个无法正确插值的对象。

你的管道需要一个类型参数,它必须是iframe的resourceUrl。。。您可以在函数中设置默认值,如:

type: string = 'resourceUrl'

或者你可以把它设置在你的管道里:

video.id.videoId  | youtube : 'resourceUrl'

或者。。。由于这只是为了将youtubeurl标记为安全的,所以您可以去掉管道的类型参数,并始终假设它标记的是资源url。

最新更新