【问题标题】:Using expand in pipe replaces values在管道中使用扩展替换值
【发布时间】:2021-12-18 19:34:43
【问题描述】:

我目前有一项服务,我通过展开获取一些模板以在视图中显示它们。这个想法是继续获取​​,直到我拥有一切。

但是,当我通过管道扩展时,它会替换值而不是添加它们,我该如何解决这个问题?

例子:

templates$: Observable<Template[]>;
let count = 0;

this.templates$ = this.templateService.getTemplates(0, 5).pipe(
      expand(result => {
        count += result.length;
        if (result.length === 5) {
          return this.templateService.getTemplates(count, 5);
        } else {
          return empty();
        }
      })
    );

【问题讨论】:

  • 哪个版本的 RxJs ?
  • 我很确定您需要在expand 之后添加一个reduce 运算符。

标签: angular typescript rxjs observable expand


【解决方案1】:

expand 不会替换值,而是在您每次收到五个一组的模板时发出。在你看来,如果你使用template$ | async,你只会看到最后一个结果。

要收集所有模板,您可以使用scan 运算符。

templates$: Observable<Template[]>;
let count = 0;

this.templates$ = this.templateService.getTemplates(0, 5).pipe(
      expand(result => {
        count += result.length;
        if (result.length === 5) {
          return this.templateService.getTemplates(count, 5);
        } else {
          return empty();
        }
      }),
      scan((acc, curr) => acc.concat(curr))
    );

如果您不想显示中间结果,也可以以同样的方式使用reduce 运算符。

【讨论】:

  • 谢谢,这正是我想要的。
猜你喜欢
  • 2020-10-05
  • 1970-01-01
  • 2020-01-18
  • 2019-07-06
  • 1970-01-01
  • 2017-04-03
  • 1970-01-01
  • 1970-01-01
  • 2021-06-30
相关资源
最近更新 更多