【问题标题】:How to resolver url sanitizer warning in angular?如何以角度解析 url sanitizer 警告?
【发布时间】:2020-02-17 23:01:33
【问题描述】:

我的 html 文件中有这个调用:

profile.html

<div mat-card-avatar *ngIf="imgResult" [ngStyle]="{ 'background-image': 'url(' + imgResult + ')' }" class="avatar">
  <mat-icon *ngIf="!imgResult">person</mat-icon>
</div>

我的组件是这样的:

profile.component.ts

import { DomSanitizer } from '@angular/platform-browser';

...

  picture: File;
  imgResult: any;

...

constructor(
    private sanitizer: DomSanitizer
  ) { }

...

  onChange(event) {
    this.picture= event.target.files[0];
    const reader = new FileReader();
    reader.readAsDataURL(this.picture);
    reader.onload = (ev: any) => {
      this.imgResult = ev.target.result;
      return this.sanitizer.bypassSecurityTrustUrl(this.imgResult);
    };
  }

图片加载正常,但我无法停止sanitizing unsafe URL value 警告。

我该怎么做?

【问题讨论】:

    标签: angular image sanitize


    【解决方案1】:

    您正确使用了消毒剂,但没有使用结果值。试试这个:

    reader.onload = (ev: any) => {
      const trustedUrl = this.sanitizer.bypassSecurityTrustStyle(`url(${ev.target.result})`);
      this.imgResult = trustedUrl;
    };
    

    并在 html 文件中使用它:

    [style.background-image]="imgResult"
    

    这个问题已经在这个话题上得到回答:WARNING: sanitizing unsafe style value url

    【讨论】:

    • 感谢@David,但它没有用。如果我使用您建议的此代码,则不会加载图片并且警告仍然存在。
    • 您可以尝试使用 bypassSecurityTrustResourceUrl 方法吗?
    • 我试过了。但问题依然存在:不加载图片和警告信息(还是一样)
    • 我找到了这个。如果您查看最受好评的答案,它与您的答案非常相似。让我们看看是否这样做,将其作为样式资源实际上是有意义的:stackoverflow.com/questions/38593515/…
    • 非常感谢!今天我花了很多时间搜索一个可以帮助我的主题,但没有找到这个主题,即使在发布这个问题时也是如此。现在它正在工作。我将保留此问题仅作为新搜索的替代方法,并在您的答案中发布链接和详细信息。
    猜你喜欢
    • 2017-08-19
    • 2021-12-29
    • 2021-04-02
    • 2019-01-26
    • 1970-01-01
    • 2018-01-22
    • 1970-01-01
    • 2019-11-19
    • 2019-04-19
    相关资源
    最近更新 更多