javascript - 如何在角度分量中嵌入视频?
问题描述
我有 angular 8 应用程序,我可以嵌入 Youtube 视频。但例如这个网址:https ://vimeo.com/346340496/11432ab1db它不会工作。那么我怎样才能让它与 vimeo 或通用解决方案一起使用。这样您就可以嵌入 youtube、vimeo、其他格式...等。
这是我的代码:
private getVideoSafeUrl(url: string): SafeResourceUrl {
const embedUrl = this.parseYoutubeUrl(url);
const safeUrl = this.domSanitizer.bypassSecurityTrustResourceUrl(
this.parseYoutubeUrl(embedUrl)
);
return safeUrl;
}
private parseYoutubeUrl(url: string): string {
let returnUrl = url;
const splitString = url.split('?');
if (splitString.length > 1) {
const baseUrl = splitString[0].replace('watch', 'embed');
let videoId;
const queryString = splitString[1];
const newQueryString = queryString
.split('&')
.reduce((prev, cur) => {
const entryArray = cur.split('=');
if (entryArray[0] === 'v') {
videoId = entryArray[1];
} else {
prev.push(cur);
}
return prev;
}, [])
.join('&');
returnUrl = `${baseUrl}/${videoId}?${newQueryString}`;
}
if (url.indexOf('youtu.be') !== -1) {
returnUrl = url.replace(/.*youtu\.be\/(.*)/g, (match, g1) => {
return `https://youtube.com/embed/${g1}`;
});
}
return returnUrl;
}
这是它的模板:
<ng-container *ngIf="is('VideoDisplay')">
<iframe
*ngIf="videoUrl.value"
class="video-iframe"
type="text/html"
[src]="getVideoSafeUrl(videoUrl.value)"
frameborder="0"
allowfullscreen
></iframe>
<mat-form-field>
<input
matInput
type="url"
name="videoUrl"
ngModel
#videoUrl="ngModel"
placeholder="Url of video"
i18n-placeholder
required
/>
<mat-error>
<app-element-edit-field-error
[errors]="videoUrl.errors"
></app-element-edit-field-error>
</mat-error>
</mat-form-field>
</ng-container>
所以我的问题是:如何让它与 viemo 或通用解决方案一起使用?
谢谢你。
解决方案
您必须扩展功能getVideoSafeUrl
以包含 vimeo 视频。
考虑这种方法
private getVideoSafeUrl(url: string): SafeResourceUrl {
let safeUrl = '';
if(this.isVimeoUrl(url)) {
safeUrl = this.domSanitizer.bypassSecurityTrustResourceUrl(
this.parseVimeoUrl(url)
);
return safeUrl;
}
safeUrl = this.domSanitizer.bypassSecurityTrustResourceUrl(
this.parseYoutubeUrl(url)
);
return safeUrl;
}
isVimeoUrl
函数检查 url 是否来自 Vimeo。
parseVimeoUrl
函数将从中提取 video_id https://vimeo.com/346340496/11432ab1db
。
在这种情况下,此值为346340496
,并计算具有结构的新 urlhttps://player.vimeo.com/video/{video_url}
有 Vimeo 开发者网站详细解释了事情。
示例嵌入 iframe
<iframe src="https://player.vimeo.com/video/346340496" width="320" height="200" frameborder="0" title="test" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
推荐阅读
- javascript - Javascript - 间隔未清除
- unicode - 如何从 .txt 文件中删除 <96>
- python - 尝试创建 Discord 欢迎/离开机器人
- mysql - 使用 order by 而不更改组的顺序
- ansible - 为什么 include_role 一次处理一个主机?
- macos - 优化 NSImageView 和 NSView 滚动性能的正确方法是什么
- java - 设置 StringBuilder 对象的最佳方法是什么?
- join - 如何使用 Mongocxx 将集合加入文档
- python - 如何保存最佳验证分数结果,即保存 6 个拆分中的第 5 个拆分
- python - 翻译文本文件中的变量