我从API中获取大量图像URL,并在angular 2 web应用程序中显示它们.有些URL被 destruct 了,我想用存储在我的Web服务器上的默认图片替换它们.是否有人建议如何测试URL,以及在状态代码404的情况下替换损坏的图像?

谢谢

推荐答案

听图像元素的error事件:

<img [src]="someUrl" (error)="updateUrl($event)">

其中,updateUrl(event) { ... }this.someUrl指定一个新值.

Plunker example

如果只想签入代码,可以使用Checking if image does exists using javascript中说明的方法

@Directive({
  selector: 'img[default]',
  host: {
    '(error)':'updateUrl()',
    '[src]':'src'
   }
})
class DefaultImage {
  @Input() src:string;
  @Input() default:string;

  updateUrl() {
    this.src = this.default;
  }
}

Directive Plunker example

Angular相关问答推荐

Angular 17上的material 工具提示的自定义样式

tabindex on button on button in MatMenu in angular不工作

Angular中的Bootstrap carousel动态属性

Angular router-outlet 未渲染

[NullInjectorError]:R3InjectorError(Standalone[_AppComponent])[]:NullInjectorError:No provider for _HttpClient

如何使用带有17角的Swiper 11.0.5元素

从Angular 前端访问ASP.NET Core 8 Web API时出现CORS错误

如何防止变量值重置?

使用Dragula时,ReactiveForm元素在拖动副本中显示不同的