I am a beginner in RxJS and I am struggling to understand how the parameters are passed in this code snippet:
import { catchError, map, Observable, of } from 'rxjs';
let obs$ = of(1,2,3,4,5);
obs$.pipe(
map(n => {
if (n === 4) {
throw 'bloody hell'
}
return n;
}),
catchError(handleError())
).subscribe(x => console.log(x));
function handleError() {
return (err: any, caught: Observable<any>): Observable<string> => {
console.log('error is ', err);
return of('I', 'II') ;
}
}
The output produced by this code is:
$ node build/catch-me.js
1
2
3
error is bloody hell
I
II
Upon inspection of the catchError function, it reveals:
export function catchError<T, O extends ObservableInput<any>>(
selector: (err: any, caught: Observable<T>) => O
): OperatorFunction<T, T | ObservedValueOf<O>>;
My inquiries are as follows:
- How does the handleError function receive the err and caught values from the catchError function without them being explicitly passed?
- Why are the err and caught values accessible only within the return function of handleError?
- Is there a distinction between the Type of the observable and the ObservableInput being passed as parameters?
- What exactly does the OperatorFunction returned by catchError do? Ultimately, it returns an observable with values I and II.