Angular 2 - 检查图像URL是有效还是损坏 [英] Angular 2 - Check if image url is valid or broken

查看:196
本文介绍了Angular 2 - 检查图像URL是有效还是损坏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从API获取大量图像URL并将其显示在角度2 Web应用程序中。一些URL被破坏,我想用我本地存储在我的网络服务器上的默认图片替换它们。有没有人有如何测试网址的建议?在状态代码404的情况下更换损坏的图像?

I am fetching a large number of image URLs from an API and display them in a angular 2 web application. Some of the URLs are broken and i want to replace them with a default picture that is stored locally on my webserver. Does anyone have a suggestion how to test the urls and in the case of status code 404 replace the broken image?

谢谢!

推荐答案

收听图像元素的错误事件:

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

其中 updateUrl(event){...} this.someUrl 分配一个新值。

Plunker示例

如果您只想签入代码,可以使用该方法在使用javascript检查图像是否存在中进行了解释

If you want to check in code only you can use the method explained in 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;
  }
}

指令Plunker示例

这篇关于Angular 2 - 检查图像URL是有效还是损坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆