LiveLoveApp logo

Solution - ThrowError Operator

Solution

import { fromEvent, throwError } from 'rxjs';
import { ajax } from 'rxjs/ajax';
import { mergeMap, tap } from 'rxjs/operators';

/**
 * DOM elements
 */
const login = document.getElementById('login') as HTMLFormElement;
const email = document.getElementById('email') as HTMLInputElement;
const password = document.getElementById('password') as HTMLInputElement;

/**
 * 1. Use the `fromEvent()` operator to add an event listener
 *    to the `login` form element's `submit` event.
 * 2. Use the `tap()` operator to invoke the `preventDefault()`
 *    method on the SubmitEvent object.
 * 3. Use the `mergeMap()` operator and if the value of the
 *    `login` or `password` input elements is falsey then throw
 *    an error using the `throwError()` operator.
 *    If the values are truthy then use the `ajax.pos()` method
 *    to post the email and password values to the API.
 * 4. Subscribe to the Observable and provide an Observer.
 */
fromEvent(login, 'submit')
  .pipe(
    tap((event) => event.preventDefault()),
    mergeMap(() =>
      !email.value || !password.value
        ? throwError(new Error('Invalid email or password'))
        : ajax.post('https://reqres.in/api/login', {
            email: email.value,
            password: password.value
          })
    )
  )
  .subscribe({
    error: (e) => console.error('observer', e),
    next: (value) => console.log('next', value),
    complete: () => console.log('complete')
  });

Let's review the solution code above:

  • First, we use the fromEvent() operator to add an event listener to the login form element's submit event.
  • The tap() operator then performs the side effect of invoking the preventDefault() method on the SubmitEvent object.
  • We do a quick truthy/falsey check of the value property for the email and password input elements.
  • If the values are falsey we use the throwError() operator to return a new Observable that immediately emits an error notification. In this solution we provided the throwError() operator with an Error object, but you could have also used a factory function.
  • If the values are truthy we use the ajax.post() method to post the email and password to the API.
  • Finally, we subscribe to the Observable and provide an Observer.