fabiobiondi

RxJS - catch error - Replace strategy

Nov 15th, 2021 (edited)
1,097
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { Component } from '@angular/core';
  2. import { catchError, map } from 'rxjs/operators';
  3. import { from, of } from 'rxjs';
  4. // import { isNumeric } from 'rxjs/internal-compatibility';
  5.  
  6. @Component({
  7.   selector: 'fb-root',
  8.   template: ` <H1>Hello Rxjs</H1> `,
  9. })
  10. export class AppComponent {
  11.   stream$ = from([5, 10, 15, 'hello', 20]);
  12.  
  13.   constructor() {
  14.     this.stream$.pipe(
  15.       map(value => {
  16.         // if (isNumeric(value)) {  // this is an alternative to the line below
  17.         if (typeof value === 'string') {
  18.           throw new Error("This is not a number")
  19.         } else {
  20.           return value;
  21.         }
  22.       }),
  23.       catchError((err) => of(0)),
  24.     ).subscribe(
  25.       (res) => {
  26.         console.log(res * res)
  27.       },
  28.       err => console.log('Error Occurred', err),
  29.       () => console.log('Stream Completed')
  30.     )
  31.   }
  32. }
  33.  
Add Comment
Please, Sign In to add comment