I am trying to set authentication headers for images called from an image tag (<img>
). To achieve this, I have created a custom pipe named secureimages
using the command ionic g pipe secureimages
.
This pipe intercepts the HTTP requests in an interceptor where I can set the necessary header. Below is the implementation of my custom pipe:
import { Pipe, PipeTransform } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
import { Observable } from 'rxjs/Observable';
@Pipe({
name: 'secureimages',
})
export class SecureImagesPipe implements PipeTransform {
constructor(private http: HttpClient, private sanitizer: DomSanitizer) { }
transform(url): Observable<SafeUrl> {
return this.http
.get(url, { responseType: 'blob' })
.map(val => this.sanitizer.bypassSecurityTrustUrl(URL.createObjectURL(val)));
}
}
And here is how I handle the interceptor:
const headers = req.headers
.set('Authorization', 'Bearer ' + token)
.append('Content-Type', 'application/json');
const reqClone = req.clone({
headers
});
return next.handle(reqClone);
To use this custom pipe in the image tag, you can do the following:
<img [attr.src]='{{this.imageURL}} | secureimages | async'/>
However, I am encountering compile errors when I try to implement this. Interestingly, using a static URL works perfectly fine. Is there a way to define dynamic image URLs in the image tag that will make use of the provided pipe?