How to handle images that might or might not load?

I feel a bit stupid right now, but I think asking can’t hurt:

I get a list of image URLs from an API. Unfortunately only some of these will actually return a “200 OK” on request, some will “404 Not Found”.

What is the best way to include these images in an Ionic app so that the 404’d images are invisible and don’t take up any space in the app?

Right now I have these “image not found” thingies:
image

1 Like

If you want your images to take up space, you can define all of them using const imgPlaceholder for some placeholder image, and change the value once your download Observable returns a value. If you want images to take up no space unless they actually exist, you could define each source to have an image placeholder of empty string, and use *ngIf to display the image only if source.trim() is not falsy. That way, if the source never loads, or if it “loads” as null or undefined, it remains invisible.

Ok that makes sense. But this would all require me to use http (or similar) to download the image instead of <img src=...>, right?

Use <img [src]="nameOfSource"> That’s the magic of Angular. You set nameOfSource to some default value, and then update it if/when the update is available.

I suspected that this again is something I just didn’t get…

And I am still confused: I see that this will automatically replace the loaded image when I mess with nameOfSource. But how would I find out if the images 404s to decide if to set nameOfSource to the URL or not?

Do you need to know? I would initialize everything assuming that everything 404s, and if a request is successful, then I’d update. That may not fit your needs, but an advantage of that approach is that that your error handling function is literally, “In case of error, do nothing.”

Do we have our wires crossed here maybe? The API gives me a list of URLs. Some return 200, some 404. To know which ones 404, I have to actually request them. Only way in angular is http, which then would make me have the image data in a string to set in the img, not the actual URL any more, right?

1 Like

http.get<string>(url).subscribe(imageSource => this.nameOfSource = imageSource);

1 Like