LoginSignup
2
1

More than 5 years have passed since last update.

取得に失敗した画像を再取得するAngularのDirective

Last updated at Posted at 2019-02-20

ネットワーク環境が常にいいとは限らず、ユーザが移動中に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 /> のように使ってください。

それではまた。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1