javascript - 如何显示作为我的对象数组中的值的 div 并将其嵌入到 html 页面中
问题描述
我有这个数组
"videos": [
{
"title": "0-1 \u00c1ngel Zald\u00edvar",
"embed": "<div style='width:100%;height:0px;position:relative;padding-bottom:56.250%;'><iframe src='https:\/\/www.scorebat.com\/embed\/v\/61860cae4badd\/?utm_source=api&utm_medium=video&utm_campaign=v3' frameborder='0' width='100%' height='100%' allowfullscreen allow='autoplay; fullscreen' style='width:100%;height:100%;position:absolute;left:0px;top:0px;overflow:hidden;'><\/iframe><\/div>"
}
]
我正在使用角度,我想访问具有视频的嵌入 div。我已经做到了
<div *ngFor="let result of data.videos">
<p> {{result.embed}} </p>
我在浏览器中的所有内容都是 div 标签,而不是嵌入视频。有人可以帮忙吗
这是我的 app.component.ts
export class AppComponent implements OnInit {stringfiedData:any;public data:any=[]constructor(private http: HttpClient) {}getData(){const url ='myApiUrl' this.http.get(url).subscribe((res)=>{this.stringifiedData = JSON.stringify(res);this.data = JSON.parse(this.stringifiedData);console.log(this.data)})}}
我已经按照@BrunoElo 的建议解析了 JSON 数据,但即使在应用了
<p [innerHTML]="result.embed"></p>
解决方案
我很确定这个问题的第二个答案会解决你的问题,但我想这有点不同
注意:不要对响应进行字符串化或解析,它已经被 HttpClient 解析过
<div [innerHTML]="result.embed | safeHtml"></div>
创建以下管道 - 并记住将其添加到模块declarations
和exports
字段(或将其添加到共享模块)
@Pipe({name: 'safeHtml'})
export class SafeHtmlPipe {
constructor(private sanitizer:DomSanitizer){}
transform(value: string) {
return this.sanitizer.bypassSecurityTrustHtml(value);
}
}
安全性:仅在您确实信任嵌入数据的来源时才使用此选项,否则您和您的应用程序将面临 XSS 攻击
推荐阅读
- javascript - 无法在组件方法中访问 $refs
- java - Files.move(...) throwing FileSystemException: The process cannot access the file because it is being used by another process
- python - 如何创建列表字典?
- firebase - 使用 Flutter Messaging 的推送通知使 Flutter 应用程序崩溃
- amazon-web-services - 如何在 AWS ALB 中为 100 多个目标组设置运行状况检查规则
- flex-lexer - 为什么我的词法分析器无法识别数字、ID 和运算符
- python - 如果用户输入不是要求的字符串值的一部分,则默认输出
- postgresql - 使用外连接时如何测试不匹配的表(多对多)
- reactjs - ReactJS markdown 编辑器组件无法渲染
- tinymce - 当我的 TinyMCE 插件在编辑框中插入标签时,输入的文本会出现在该标签内而不是外部。我该如何避免这种情况?