如何在 angular 中解析 url 消毒剂警告?
How to resolver url sanitizer warning in angular?
我的 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
警告。
我该怎么做?
您正确使用了消毒剂,但没有使用结果值。试试这个:
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
我的 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
警告。
我该怎么做?
您正确使用了消毒剂,但没有使用结果值。试试这个:
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