Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - 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. 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?

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
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:

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

where updateUrl(event) { ... } assigns a new value to 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

@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 Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.5k users

...