[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>');
});
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 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