[RxJS] catchError

catchError will complete the observable, so be careful where you put the catchError:

import { fromEvent, empty } from 'rxjs';
import { ajax } from 'rxjs/ajax';
import {
  debounceTime,
  pluck,
  distinctUntilChanged,
  switchMap,
  catchError
} from 'rxjs/operators';

const BASE_URL = 'https://api.openbrewerydb.org/breweries';

//elems
const inputBox = document.getElementById('text-input');
const typeaheadContainer = document.getElementById('typeahead-container');

// streams
const input$ = fromEvent(inputBox, 'keyup');

input$
  .pipe(
    debounceTime(200),
    pluck('target', 'value'),
    distinctUntilChanged(),
    switchMap(searchTerm => ajax.getJSON(
      `${BASE_URL}?by_name=${searchTerm}`
      ).pipe(
        /*
         * catchError receives the error and the
         * observable on which the error was caught
         * (in case you wish to retry). In this case,
         * we are catching the error on the ajax
         * observable returned by our switchMap
         * function, as we don't want the entire
         * input$ stream to be completed in the
         * case of an error.
         */
        catchError((error, caught) => {
          /*
           * In this case, we just want to ignore
           * any errors and hope the next request
           * succeeds so we will just return an 
           * empty observable (completes without
           * emitting any values).
           * 
           * You can also use the EMPTY import, 
           * which is just a shortcut for empty(). 
           * Behind the scenes empty() returns the
           * EMPTY constant when a scheduler is not provided.
           * ex. import { EMPTY } from 'rxjs';
           * return EMPTY;
           * https://github.com/ReactiveX/rxjs/blob/fc3d4264395d88887cae1df2de1b931964f3e684/src/internal/observable/empty.ts#L62-L64
           */
          return empty();
        })
      )
    )
  )
  .subscribe((response: any[]) => {
    // update ui
    typeaheadContainer.innerHTML = response.map(b => b.name).join('<br>');
  });

 

posted @   Zhentiw  阅读(112)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
· 上周热点回顾(2.17-2.23)
历史上的今天:
2018-10-20 [Unit Testing] Mock an HTTP request using Nock while unit testing
2015-10-20 [AngularJS] Enable Animations Explicitly For A Performance Boost In AngularJS
2015-10-20 [AngularJS + Unit Testing] Testing Directive's controller with bindToController, controllerAs and isolate scope
点击右上角即可分享
微信分享提示