我正在努力清理复杂的可观察物链。我遍历了从秋田商店返回的商品数组,并对每个商品执行操作,然后存储它们(如果已被修改)。我目前有一个可行的解决方案,但我想知道是否有更清洁或更直接的方法来处理此链。
我尝试查找一些带有可观察对象的数组循环实例,但没有发现任何复杂的事物或尝试做与我相似的事情。
下面这个例子很奏效,但这似乎并不是其最佳的可观察对象和运算符实践。
public fetchAdditionalSavedSearchDetails(): Observable<any> {
return this.savedSearchQuery.selectAll().pipe(
// Debounce to prevent from calling to frequently
debounceTime(500),
switchMap((savedSearches) => {
return forkJoin(
// Loop through saved searches and return observable
savedSearches.map((savedSearch) => of(savedSearch).pipe(
// default modified to false
switchMap((savedSearch) => of([savedSearch, false])),
switchMap(([savedSearch, modified]) => {
const search: ISavedSearch = savedSearch as ISavedSearch;
if (search.searchTotalCount === undefined) {
// todo: implement fetching search count
return of([{ ...search, searchTotalCount: 0 }, true]);
}
return of([savedSearch, modified]);
}),
switchMap(([savedSearch, modified]) => {
const search: ISavedSearch = savedSearch as ISavedSearch;
if (search.scheduledExports === undefined) {
return this.scheduledExportService.fetchAllScheduledExportsForSavedSearch(search).pipe(
mergeMap((scheduledExports) => of([{ ...search, scheduledExports }, true]))
);
}
return of([savedSearch, modified]);
})
))
).pipe(tap((response) => {
// Prevent akita store from triggering changes on each update of entity
applyTransaction(() => {
response.forEach((searchResp: Array<ISavedSearch | boolean>) => {
const search: ISavedSearch = searchResp[0] as ISavedSearch;
const modified: boolean = searchResp[1] as boolean;
if (modified) {
this.savedSearchStore.update(search.id, search);
}
});
});
}));
})
);
}
答案 0 :(得分:0)
我没有阅读所有代码,但是从您的要求来看,我认为以下更改可能会对您有所帮助。
您可以更改此代码:
switchMap((savedSearches) => {
return forkJoin(
// Loop through saved searches and return observable
savedSearches.map((savedSearch) => of(savedSearch).pipe(
对此:
switchMap(savedSearches => savedSearches),
// Continue with your next operator here
应该做到:
通常,这是当您必须在其他管道内进行管道操作时,您做错了一个信号(这是个例外)。