【发布时间】:2019-10-13 06:44:20
【问题描述】:
我有一个组件在呈现虚拟列表中的最后一项时触发onScrollEnd 事件。此事件将发出一个新的 API 请求以获取下一页并使用 scan 运算符将它们与以前的结果合并。
此组件还有一个搜索字段,可触发onSearch 事件。
触发搜索事件时,如何清除scan算子之前累积的结果?还是我需要在这里重构我的逻辑?
const loading$ = new BehaviorSubject(false);
const offset$ = new BehaviorSubject(0);
const search$ = new BehaviorSubject(null);
const options$: Observable<any[]> = merge(offset$, search$).pipe(
// 1. Start the loading indicator.
tap(() => loading$.next(true)),
// 2. Fetch new items based on the offset.
switchMap(([offset, searchterm]) => userService.getUsers(offset, searchterm)),
// 3. Stop the loading indicator.
tap(() => loading$.next(false)),
// 4. Complete the Observable when there is no 'next' link.
takeWhile((response) => response.links.next),
// 5. Map the response.
map(({ data }) =>
data.map((user) => ({
label: user.name,
value: user.id
}))
),
// 6. Accumulate the new options with the previous options.
scan((acc, curr) => {
// TODO: Dont merge on search$.next
return [...acc, ...curr]);
}
);
// Fetch next page
onScrollEnd: (offset: number) => offset$.next(offset);
// Fetch search results
onSearch: (term) => {
search$.next(term);
};
【问题讨论】:
标签: javascript angular typescript rxjs rxjs-pipeable-operators