RxJS zip()运算符无法按预期工作。它总是在不触发任何值的情况下完成

问题描述 投票:0回答:2

场景:当有一个包含大量元素的可观察对象时,例如450+,我想将这些元素添加到100个元素的批量中的不同可观察对象中。

你可以在这里找到一个有效的例子:https://stackblitz.com/edit/rxjs-au9pt7?file=index.ts @martin为我提供了这个问题的答案的一部分:Take N values from Observable until its complete based on an event. Lazy loading a multi select list

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>

非常感谢提前,非常感谢任何帮助。

javascript angular rxjs reactive-programming rxjs6
2个回答
0
投票

我认为你是拉链的误解,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>

0
投票

由于某些奇怪的原因,RxJS版本6.3.3导致了这个问题。升级到RxJS 6.4.0解决了这个问题。

© www.soinside.com 2019 - 2024. All rights reserved.