I have a pipe function on my observable where i change value of response to empty array if result is null, or undefined.
obs.pipe(
map(res => {
// pipe and map function to return empty array if resource did not return result
return res ?? [];
})
);
i am using this functionality on multiple places and I am wondering if I can create some handler so I would not need to reuse this code.
My expectations:
this.loadCountries().pipe(defaultEmptyArrayPipe)
Thank you
CodePudding user response:
you can achieve it by wrapping it with function which receives observable and returns an observable for example:
function defaultEmptyArrayPipe <T>(source$: Observable<T>): Observable<T> {
return source$.pipe(
map(res => {
return res ?? [];
})
)
}
then call it as u wanted to:
this.loadCountries().pipe(defaultEmptyArrayPipe)
CodePudding user response:
You can just wrap it with pipe and save it for reuse
const defaultEmptyArrayPipe = pipe(map(res => {
// pipe and map function to return empty array if resource did not return result
return res ?? [];
}))
this.loadCountries().pipe(defaultEmptyArrayPipe)