Implementing a JWT authorized endpoint for images has made it impossible to directly link to image urls in HTML.
To work around this issue, we have created an async pipe that loads the image with proper authorization (handled by an HTTP interceptor, not shown) and sets the img.src attribute to an "object" URL.
Here is how it looks in the HTML:
<img [attr.src]="environment.apiUrl + 'users/image/' + userId | secureImage | async" alt="Avatar" />
The Pipe used is as follows:
import { Pipe, PipeTransform } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
@Pipe({
name: 'secureImage'
})
export class SecureImagePipe implements PipeTransform {
constructor(private http: HttpClient, private sanitizer: DomSanitizer) { }
transform(url): Observable<SafeUrl> {
return this.http
.get(url, { responseType: 'blob' })
.pipe(map(val => this.sanitizer.bypassSecurityTrustUrl(URL.createObjectURL(val))));
}
}
In the GIF demonstration provided, when the image changes from the static plus sign to the dynamically loaded homer brain using the pipe, there is a brief flicker displaying the "image not found" text along with the alt text (Avatar).
We are looking for suggestions on how to eliminate or reduce this flickering effect.
UPDATE: Removing the "alt" attribute removes the "broken image" icon, resulting in a smoother display.
For example, changing from this:
<img [attr.src]="environment.apiUrl + 'users/image/' + userId | secureImage | async" alt="Avatar" />
to this:
<img [attr.src]="environment.apiUrl + 'users/image/' + userId | secureImage | async" />
We will keep this question open as some users may require the alt attribute, making our solution unsuitable for them.