有没有办法简化具有类似订阅的条件切换映射操作?



我正在订阅一个搜索框,并根据值是否为空或包含字符,从不同的可观察量中获取搜索结果。

this.myservice.searchByKeyword.pipe(
switchMap(keyword => {
if (!keyword || keyword.length === 0) { // true if keyword is empty
return this.someService.GetEmptySearch();
} 
return this.someService.GetItems(keyword); 
}),
takeUntil(unsubOnDestroy$)
).subscribe({
next: articles: Article[] => {
// Here the result should be handled in the same way, except that if the GetItems observable is returned, I would like to do some conditional with the result.
...
if (getItems was returned) { // pseudocode
// blah blah
}
}
})

我尝试返回一个带有枚举的嵌套可观察对象,以指示条件是否应该运行,但我还没有让它工作。

我可以将整个订阅块移动到例如 switchMap 中的 tap 运算符中。但这会导致重复的代码,我想避免它。

可以将管道添加到GetItems调用:

this.myservice.searchByKeyword.pipe(
switchMap(keyword => {
if (!keyword || keyword.length === 0) { // true if keyword is empty
return this.someService.GetEmptySearch();
} 
return this.someService.GetItems(keyword).pipe(
map((items) => // do what you want here)
)
}),
takeUntil(unsubOnDestroy$)
).subscribe({
next: articles: Article[] => {
}
});

此外,感觉结果直接用于模板。可以将Observable存储在组件中,并使用异步管道直接使用它。这将通过takeUntilsubscribe减少代码开销:

readonly articles$ = this.myservice.searchByKeyword.pipe(
switchMap(keyword => {
if (!keyword || keyword.length === 0) { // true if keyword is empty
return this.someService.GetEmptySearch();
} 
return this.someService.GetItems(keyword).pipe(
map((items) => // do what you want here)
)
})
);

另一点,考虑到两个调用都来自同一个服务,最好在服务内部使用关键字和映射来执行逻辑,而不是在组件中

最新更新