⚠️ This lesson is retired and might contain outdated information.

Handle Image Loading Errors in Vue.js with RxJS and domStreams

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 9 months ago

When an image fails to load, it triggers an error event. You can capture the error event and merge it with your image loading stream to provide a backup image when things go wrong. This lesson shows how to load a placeholder image if the main image fails to load.

Instructor: [00:00] now imagine that there's an error in our URL and our image fails to load. If I click here and you can see that the image fails to load in the console, you can actually handle that in an interesting way because image has an error event. I'm going to stream this in as an observable.

[00:19] This domstream can be image error, and make sure to define it in our domstream, so image error. Then, our image can be an observable merge of this stream and an error stream. I'm going to extract this out real quick. I'll call this, "Load Image" stream. Then, I want a fail image stream, so I'll call this, "Fail Image."

[00:45] The Fail Image is this .image error mapped to whatever image you want to provide as a default. I'm going to copy and paste a placeholder service. Now our image stream becomes a merge, so observable merge of Load Image and Fail Image.

[01:09] Now if I click, you see we get our image failure. It failed, and we handled it with a placeholder. If I put my proper URL back in and hit Save and click, it'll properly load the image...

Paul Perry
Paul Perry
~ 6 years ago

Hi all,

I'm back again, hopefully helping people with rxjs 6 related issues - make sure your imports look like this:

import { from, merge } from 'rxjs'
import { pluck, switchMap, map, mapTo } from 'rxjs/operators';

Then, in your image code:

    const loadImage$ = getName$.pipe(
      pluck('image'), 
      map(image => `https://starwars.egghead.trainin/${image}`)
    );
  
    const failImage$ = this.imageError$.pipe(
      mapTo(`http://via.placeholder.com/400x400`)
    )
    
    const image$ = merge(
      loadImage$,
      failImage$
    )

Hope that helps!

Stu
Stu
~ 5 years ago

How do you handle an error in this.$http.get() ?

Markdown supported.
Become a member to join the discussionEnroll Today