Angular 10 - 检测图像是否仅存在于客户端,否则默认图像

E J*_*rod 4 rest url image angular

我需要知道如何使用 Angular 检测图像是否存在(仅在客户端)。我听说我们可以使用超时功能设置默认图像,但我不知道如何捕获 404 错误。

我只需要在 getResourceImg() 上编写代码,正如Angular 的风格指南所说

资源-ui.component.ts

  @Input() resource: IResourcePublished;
  // ...

  resourceImgUrlLogoDefault: string = 'assets/images/logo_default.png';
  resourceImgUrl: string;

  constructor(private modalService: NgbModal) {}

  ngOnInit(): void {
    this.resourceImgUrl = this.getRessourceImg(this.resource);
  }

  getResourceImg(resource: IResourcePublished): string {

    return 'assets/images/screen-resources/' + resource.id + '.png';
  }

  //..
Run Code Online (Sandbox Code Playgroud)

这是模板(用 生成*ngFor="let resource of resources"):

资源-ui.component.html

  @Input() resource: IResourcePublished;
  // ...

  resourceImgUrlLogoDefault: string = 'assets/images/logo_default.png';
  resourceImgUrl: string;

  constructor(private modalService: NgbModal) {}

  ngOnInit(): void {
    this.resourceImgUrl = this.getRessourceImg(this.resource);
  }

  getResourceImg(resource: IResourcePublished): string {

    return 'assets/images/screen-resources/' + resource.id + '.png';
  }

  //..
Run Code Online (Sandbox Code Playgroud)

yur*_*zui 5

您可以创建可重用的指令,例如:

后备-img.directive.ts

import { Directive, Input, HostBinding, HostListener } from '@angular/core';

@Directive({
  selector: 'img[fallback]'
})
export class FallbackImgDirective {
  @Input()
  @HostBinding('src')
  src: string;

  @Input() fallback: string;

  @HostListener('error')
  onError() {
    this.src = this.fallback;
  }
}
Run Code Online (Sandbox Code Playgroud)

用法

<img src="http://unknown/404.jpg" fallback="https://via.placeholder.com/150" alt="">
Run Code Online (Sandbox Code Playgroud)

NG 运行示例

  • HostListener 允许我们监听宿主元素的事件。本例中的宿主元素是 img,它可能有错误事件。HostBinding 意味着该 src 字段的更改将更新主机元素的 src 属性 (2认同)