【问题标题】:Angular 2 "unsafe value used in a resource URL context" in *ngFor="let.." [duplicate]*ngFor="let.."中的Angular 2“资源URL上下文中使用的不安全值” [重复]
【发布时间】:2018-05-03 18:32:56
【问题描述】:

我从 REST API 获得了几篇文章并用以下方式解析它们:

<div class="row" *ngFor="let Post of Posts">
  Some output
</div>

其中一些有 youtube_url,但大多数没有,所以我使用以下 sn-p 为那些带有 youtube_url 的帖子添加 youtube iframe。

<div class="embed-responsive embed-responsive-16by9" *ngIf="Post.youtube_url" style="margin-bottom: 5px;">
  <iframe class="embed-responsive-item" [src]=Post.youtube_url allowfullscreen></iframe>
</div>

我现在的问题是我收到以下错误:

ERROR Error: unsafe value used in a resource URL context (see http://g.co/ng/security#xss)
at DomSanitizerImpl.sanitize (platform-browser.js:4506)
at setElementProperty (core.js:10753)
at checkAndUpdateElementValue (core.js:10673)
at checkAndUpdateElementInline (core.js:10607)
at checkAndUpdateNodeInline (core.js:13889)
at checkAndUpdateNode (core.js:13836)
at debugCheckAndUpdateNode (core.js:14729)
at debugCheckRenderNodeFn (core.js:14708)
at Object.eval [as updateRenderer] (HomeComponent.html:17)
at Object.debugUpdateRenderer [as updateRenderer] (core.js:14693)

我发现了多个关于这个问题的问题,但没有一个符合我的上述条件。

那么,我该怎么做呢?

【问题讨论】:

    标签: angular


    【解决方案1】:

    你需要告诉你的 dom url 是安全的。你可以通过在你的应用中实现这个管道来做到这一点:

    import { Pipe, PipeTransform } from '@angular/core';
    import { DomSanitizer } from "@angular/platform-browser";
    
    @Pipe({ name: 'safeUrl' })
    export class SafeUrlPipe implements PipeTransform {
        constructor(private sanitizer: DomSanitizer) { }
    
        transform(url) {
            return this.sanitizer.bypassSecurityTrustResourceUrl(url);
        }
    }
    

    ...然后像这样在您的模板中使用它:

    <div class="embed-responsive embed-responsive-16by9" *ngIf="Post.youtube_url" style="margin-bottom: 5px;">
          <iframe class="embed-responsive-item" [src]="Post.youtube_url | safeUrl" allowfullscreen></iframe>
    </div>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-30
      • 2016-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多