gpt4 book ai didi

javascript - 如何通过 Angular 中的异步 base64 字符串显示图像

转载 作者:行者123 更新时间:2023-12-01 15:37:10 24 4
gpt4 key购买 nike

我使用 Angular 的 http 客户端从后端加载 base64 字符串。收到字符串后,图像应立即显示在 View 中。我尝试了下面的代码,但 Angular 做出了响应,因为由于 XSS 安全策略,字符串无法加载到 View 中。

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 来信任字符串。如果字符串是静态的,这可以正常工作,但我无法为异步情况正确设置它。
public image: string = this.sanitizer.bypassSecurityTrustUrl("data:image/png;base64,...");
<img [src]="image" />

我也通过 DOM 或 ViewChild 尝试了很多东西,但我找不到适合我用例的解决方案。如何显示通过异步调用获得的 base64 字符串中的图像?

最佳答案

我建议你几个选择:
使用自定义管道将您的字符串转换为 SafeResourceUrl
safe.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" />
Ng-run Example
手动将字符串转换为 SafeResourceUrl
ts
image$: ReplaySubject<SafeResourceUrl> = new ReplaySubject(1);
...
this.image$.next(this.sanitizer.bypassSecurityTrustResourceUrl(response.imageString));
Ng-run Example

关于javascript - 如何通过 Angular 中的异步 base64 字符串显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62252634/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com