方案:当具有许多元素的可观察值时,例如450 ,我想将这些元素添加到可在100个元素的批处理中可观察到的其他元素。
您可以在这里找到一个有效的示例:https://stackblitz.com/edit/rxjs-au9pt7?file=index.ts @martin为我提供了这个问题的答案的一部分:将N值从可观察到根据事件的完成。懒惰的多选择列表
stackblitz的工作方式就像魅力,但我正在努力以Angular实施此功能。可观察到的(ZIP操作员的结果)在没有触发任何单个值的情况下完成,但是如您在工作示例中所见,它的工作原理非常好。我一定缺少一些东西,但我不确定是什么。
component.ts
import { Component, AfterViewInit } from '@angular/core';
import { zip, Observable, fromEvent, range } from 'rxjs';
import { map, bufferCount, startWith, scan } from 'rxjs/operators';
import { MultiSelectService, ProductCategory } from './multiselect.service';
@Component({
selector: 'multiselect',
templateUrl: './multiselect.component.html',
styleUrls: ['./multiselect.component.scss']
})
export class MultiselectComponent implements AfterViewInit {
SLICE_SIZE = 100;
categories$: Observable<Array<ProductCategory>>;
constructor(private data: MultiSelectService) {
this.categories$ = data.categories$;
}
ngAfterViewInit() {
const loadMore$ = fromEvent(document.getElementsByTagName('button')[0], 'click');
const data$ = range(450);
zip(
data$.pipe(bufferCount(this.SLICE_SIZE)),
loadMore$.pipe(startWith(0)),
).pipe(
map(results => results[0]),
scan((acc, chunk) => [...acc, ...chunk], []),
).subscribe({
next: v => console.log(v),
complete: () => console.log('complete'),
});
}
}
template.html
<button>load more</button>
非常感谢,任何帮助都非常感谢。
我认为您正在误解zip,zip会交错两个可观察的结果。
const { from, zip } = rxjs;
const nums$ = from([1, 2, 3, 4]);
const strings$ = from(['a', 'b', 'c', 'd']);
zip(nums$, strings$).subscribe(([num, str]) => { console.log(`${num} - ${str}`); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.4.0/rxjs.umd.min.js"></script>
出于某种奇怪的原因,RXJS版本6.3.3引起了问题。升级到RXJS 6.4.0解决了问题。