首页 > 解决方案 > 如何显示作为我的对象数组中的值的 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>

标签: javascripthtmljsonangularuser-interface

解决方案


我很确定这个问题的第二个答案会解决你的问题,但我想这有点不同

注意:不要对响应进行字符串化或解析,它已经被 HttpClient 解析过

<div [innerHTML]="result.embed | safeHtml"></div>

创建以下管道 - 并记住将其添加到模块declarationsexports字段(或将其添加到共享模块)

@Pipe({name: 'safeHtml'})
export class SafeHtmlPipe {
  constructor(private sanitizer:DomSanitizer){}

  transform(value: string) {
    return this.sanitizer.bypassSecurityTrustHtml(value);
  }
}

安全性:仅在您确实信任嵌入数据的来源时才使用此选项,否则您和您的应用程序将面临 XSS 攻击


推荐阅读