在 Angular 中嵌入 HTML5 <video> 元素,将其源代码置于 [src] 指令下



我正试图在我的Angular应用程序中使用HTML5 video元素嵌入一个示例视频。当我使用[src]指令将源属性设置为字符串(硬编码(URL时,视频会成功嵌入,但当我将相同的URL(例如,_videoUrl字段(设置为_videoUrlthis._videoUrl时,视频就会像被禁用一样崩溃。最后一件事,当我在浏览器上检查视频元素时,我看到它的URL被解析并正确地放置在src属性中,无论如何,它最初是[src]="this._videoUrl",仍然不起作用,所以,有人知道这里发生了什么吗?

注意:

  1. 该视频是托管在AWS S3上的一个简单视频
  2. 我使用的是Angular 9
  3. 我在这两种情况下都使用[src],并且从未按原样使用src属性

代码:

film.compontent.html

<div class="text-center col-2nd">
<span style="display: block;">
<video controls width="600px" height="300px">
<source [src]="_videoUrl" type="video/mp4"/>
</video>
</span>
<span style="display: block; font-size: 26px;">
Official trailer
</span>
</div>

薄膜组件.ts

@Component({
selector: 'app-film',
templateUrl: './film.component.html',
styleUrls: ['./film.component.css']
})
export class FilmComponent implements OnInit {
_videoUrl;
_videoStringUrl;
constructor(
private route: ActivatedRoute,
private server: ServerService,
private sanitizer: DomSanitizer,
private cartService: CartService
) { }
ngOnInit() {
this._videoStringUrl = 'https://khadjiev-rk.s3.amazonaws.com/file_example_MP4_480_1_5MG.mp4';
this._videoUrl = 
this.sanitizer.bypassSecurityTrustUrl(this._videoStringUrl);
}
}

演示使用sanizer的管道来表示绑定是可信的

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml, SafeStyle, SafeScript, SafeUrl, SafeResourceUrl } from '@angular/platform-browser';
@Pipe({
name: 'safe'
})
export class SafePipe implements PipeTransform {
constructor(protected sanitizer: DomSanitizer) {}

public 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}`);
}
}
}

您的绑定

[src]="_videoUrl | safe : 'url'"

DomSanitizer注入组件并使用类似的东西

get url() {
return this.sanitizer.bypassSecurityTrustUrl(this._videoUrl);
}

[src]="url"

最新更新