代码之家  ›  专栏  ›  技术社区  ›  DarkW1nter

角度6-捕获丢失的图像源,然后尝试重置相同的源

  •  0
  • DarkW1nter  · 技术社区  · 6 年前

    我有一个用户可以添加到的blob列表。 如果我有一个新添加的图像在刷新列表时还没有完成上传,我会发现错误如下,并且可以看到函数在什么时候启动:

    <img src="https://MyUrl/thumbnails/{{ blob.name }}" width="125" id="MyImg"
            (error)="error()"/>
    

    是否可以将该图像传递到错误函数以重试设置源?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Andrei Tătar    6 年前

    您可以创建一个绑定 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)。

    推荐文章