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

InstructorJohn Lindquist

Share this video with your friends

Send Tweet

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.

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
~ 5 years ago

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