Angular中使用safe pipe加载YouTube视频时遇unsafe value资源URL错误
解决Angular嵌入YouTube视频的“unsafe value used in a resource URL context”错误
问题出在iframe的src属性绑定方式上:你使用了插值语法{{video | safe}},这种方式会让Angular依然将处理后的URL视为普通字符串,而非安全的资源URL。
修复步骤:
修改iframe的src绑定方式
将原本的插值语法改为Angular的属性绑定语法:<iframe class="embed-responsive-item" [src]="video | safe" frameborder="0" allowfullscreen></iframe>确认SafePipe的完整性
确保你的SafePipe正确注入了DomSanitizer,并且实现完整:import { Pipe, PipeTransform } from '@angular/core'; import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser'; @Pipe({ name: 'safe' }) export class SafePipe implements PipeTransform { constructor(private sanitizer: DomSanitizer) {} transform(url: string): SafeResourceUrl { return this.sanitizer.bypassSecurityTrustResourceUrl(url); } }模块中声明SafePipe
在你的Angular模块(如AppModule)的declarations数组中加入SafePipe,确保pipe能被模板识别:@NgModule({ declarations: [ // ...其他组件、指令 SafePipe ], // ...其他配置 }) export class AppModule { }
验证URL格式
确保item.config.videos中的每个video值是标准的YouTube嵌入URL,比如https://www.youtube.com/embed/-fclle4fEuU,而非普通视频页面URL。
内容的提问来源于stack exchange,提问作者Leonardo Lima
相关产品推荐
相关产品推荐

