HTML
<img>
标签不允许向加载图像的请求添加标头。但是,您可以编写一个自定义管道,通过 HttpClient
加载图像,并从响应中生成一个 base64 字符串。这允许您直接或使用拦截器添加请求标头:
@Pipe({
name: 'authenticatedImage',
standalone: true,
})
export class AuthenticatedImagePipe implements PipeTransform {
private http = inject(HttpClient);
transform(src: string): Observable<string> {
return this.http.get(src, {
responseType: 'blob',
// add headers here if necessary, or better use an interceptor
}).pipe(
switchMap(
(data: Blob) =>
new Observable<string>(observer => {
const reader = new FileReader();
if (data) {
reader.readAsDataURL(data);
}
reader.onload = () => {
const result = reader.result as string;
observer.next(result);
observer.complete();
};
reader.onerror = error => observer.error(error);
if (!data|| reader.error) {
observer.error(new Error('Image could not be loaded'));
}
}),
),
);
}
}
并像下面这样使用它:
<img [src]="'http://whatever.com?filename=myimage.jpg' | authenticatedImage | async"/>
关于此方法的一些注意事项:
img
会显示“图片损坏”符号