Reputation: 99
I use the http client from Angular to load a base64 string from the backend. As soon as the string is received, the image should be displayed in the view. I tried the code below, but Angular responded because the string cannot be loaded into the view due to XSS security policies.
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)" />
So I tried to use the DomSanitizer to trust the string. If the string is static, this works fine, but I wasn't able to set it up properly for the async case.
public image: string = this.sanitizer.bypassSecurityTrustUrl("data:image/png;base64,...");
<img [src]="image" />
I tried a lot of things also via DOM or ViewChild, but I could not find a solution for my use case. How can I display an image from a base64 string that I get via an async call?
Upvotes: 4
Views: 2705
Reputation: 214067
I'd suggest you several options:
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" />
ts
image$: ReplaySubject<SafeResourceUrl> = new ReplaySubject(1);
...
this.image$.next(this.sanitizer.bypassSecurityTrustResourceUrl(response.imageString));
Upvotes: 6