Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
344 views
in Technique[技术] by (71.8m points)

javascript - 角度2-检查图片网址是否有效或损坏(Angular 2 - Check if image url is valid or broken)

I am fetching a large number of image URLs from an API and display them in a angular 2 web application.(我正在从API提取大量图像URL,并将其显示在angular 2 Web应用程序中。)

Some of the URLs are broken and i want to replace them with a default picture that is stored locally on my webserver.(一些URL已损坏,我想用存储在本地Web服务器上的默认图片替换它们。) Does anyone have a suggestion how to test the urls and in the case of status code 404 replace the broken image?(有没有人建议如何测试网址,并且在状态码404的情况下替换损坏的图片?)

Thanks!(谢谢!)

  ask by Jakob Svenningsson translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Listen to the error event of the image element:(监听图像元素的error事件:)

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

where updateUrl(event) { ... } assigns a new value to this.someUrl .(其中updateUrl(event) { ... }this.someUrl分配一个新值。)

Plunker example(柱塞示例)

If you want to check in code only you can use the method explained in Checking if image does exists using javascript(如果只想检入代码,则可以使用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(指令柱塞示例)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...