在 Angular 6 中应用 DomSanitizationService

Apply DomSanitizationService in Angular 6

目前我必须支持一个Angular项目。

有关于不安全图像的安全问题报告,Chrome控制台下显示的错误信息如下:

unsafe:data:image/png;base64,:1 GET unsafe:data:image/png;base64, net::ERR_UNKNOWN_URL_SCHEME

我在google附近,发现我需要使用 DomSanitizationService 来清理值。但是,我在编写代码时一直遇到问题,我怀疑是语法错误。以下是我的 HTML 代码:

<img src="{{ _DomSanitizationService.bypassSecurityTrustUrl(captchaSrc) }}"  height="auto" width="100%" id="captcha-img" />

下面是我的 TypeScript 文件代码:

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

captchaSrc: string = 'data:image/png;base64,';

constructor(
    public _DomSanitizationService: DomSanitizer
  ) {
  }

this.captchaSrc += this.captcha.captchaImg;

我在 chrome 控制台中遇到以下错误:

unsafe:SafeValue must use [property]=binding: data:image/png;base64, (see http://g.co/ng/security net::ERR_UNKNOWN_URL_SCHEME

对我犯的错误有什么想法吗?

***** 编辑 ***** 在我参考了 Adrita Sharma 的回答后,我仍然有一些问题,这是我通过方法,但它没有生效:

startRegistration(via: string): void {
     this.sharedService.generateCaptcha().subscribe(response => {
     this.captcha = response;
     this.captchaSrc += this.captcha.captchaImg;
     this._DomSanitizationService.bypassSecurityTrustUrl(this.captchaSrc);
    });
}

这样试试:

constructor( public _DomSanitizationService: DomSanitizer) {
   _DomSanitizationService.bypassSecurityTrustUrl(this.captchaSrc)
}

模板:

<img [src]="captchaSrc" height="auto" width="100%" id="captcha-img" />

编辑:

yourMethod(){
    this.captchaSrc = this._DomSanitizationService.bypassSecurityTrustUrl('data:image/png;base64,' + this.captchaSrc)
}

试一试 .ts

import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
export class TESTComponent {
  _imageUrlNotSanitized: SafeUrl;
  image: string;
  constructor(private sanitizer: DomSanitizer) {}
  ngOnInit() {
      this._imageUrlNotSanitized = this.sanitizer.bypassSecurityTrustUrl(this.image);
}
}

.html <img [src]="_imageUrlNotSanitized">