ネットワーク環境が常にいいとは限らず、ユーザが移動中にWebを利用している時、画像のレンダリングが終わる前にネットワークがつながらなくなることもあります。そうすると、レンダリングしようとした画像が表示されないままWebを使ってもらうことになるので、再取得のDirectiveを書きました。
import { Directive, Input, HostBinding, HostListener } from '@angular/core';
@Directive({
selector: 'img[appDefaultImg]',
})
export class DefaultImgDirective {
@HostBinding('attr.src') @Input() src;
@HostListener('error') retryGetImage() {
setTimeout(() => {
const dd = new Date();
if (this.src.match(/\?/)) {
this.src = this.src + '&t=' + dd.getTime();
} else {
this.src = this.src + '?t=' + dd.getTime();
}
}, 5000);
}
}
errorイベントをハンドリングして、srcに格納されている画像を5秒おきに見にいきます。 <img src='' appDefaultImg />
のように使ってください。
それではまた。