[英]How to display an image via an async base64 string in Angular
我使用來自 Angular 的 http 客戶端從后端加載 base64 字符串。 收到字符串后,圖像應立即顯示在視圖中。 我嘗試了下面的代碼,但是 Angular 響應了,因為由於 XSS 安全策略,無法將字符串加載到視圖中。
public image$: ReplaySubject<string> = new ReplaySubject(1);
public loadImage(): void {
...
this.deviceService.getItem(deviceId, itemId).then((response) => {
this.image$.next(response.imageString);
}
}
<img [src]="(image$ | async)" />
所以我嘗試使用 DomSanitizer 來信任字符串。 如果字符串是 static,這工作正常,但我無法為異步情況正確設置它。
public image: string = this.sanitizer.bypassSecurityTrustUrl("data:image/png;base64,...");
<img [src]="image" />
我也通過 DOM 或 ViewChild 嘗試了很多東西,但我找不到適合我用例的解決方案。 如何顯示通過異步調用獲得的 base64 字符串中的圖像?
我建議你幾個選擇:
安全.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Pipe({
name: 'safe'
})
export class SafePipe implements PipeTransform {
constructor(private sanitizer: DomSanitizer) {}
transform(url) {
return this.sanitizer.bypassSecurityTrustResourceUrl(url);
}
}
html
<img [src]="image$ | async | safe" />
ts
image$: ReplaySubject<SafeResourceUrl> = new ReplaySubject(1);
...
this.image$.next(this.sanitizer.bypassSecurityTrustResourceUrl(response.imageString));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.