您可以创建一个绑定
src
在上重试(设置为空,并再次设置为带超时的绑定值)
error
. 例如,这里有一些与您需要的非常相似的东西,以及一个非常好的起点:
https://medium.com/@sub.metu/angular-fallback-for-broken-images-5cd05c470f08
它基本上使用了一个回退URL,以防SRC失败。
类似这样(快速修改,未测试):
import { Directive, OnDestroy, Input, ElementRef } from '@angular/core';
@Directive({
selector: 'img[retrySrc]',
host: {
'(error)': 'loadError()',
'(load)': 'clearTimer()',
}
})
export class RetrySrcDirective implements OnDestroy {
private _retrySrc: string;
private _timer;
constructor(
private element: ElementRef<HTMLImageElement>,
) {
}
@Input()
set retrySrc(value: string) {
this.clearTimer();
this._retrySrc = value;
this.element.nativeElement.src = value; //each set on src triggers a new request in google Chrome
}
ngOnDestroy() {
this.clearTimer();
}
loadError() {
this.clearTimer();
this._timer = setTimeout(() => this.element.nativeElement.src = this._retrySrc, 5000);
}
clearTimer() {
if (this._timer) {
clearTimeout(this._timer);
delete this._timer
}
}
}
你使用它就像:
<img [retrySrc]="'https://MyUrl/thumbnails/'+blob.name">
或者你可以做常规的
HttpClient
在指令中定期请求,并在收到200响应后设置SRC(同时使用一些默认SRC)。