【问题标题】:Issue with RXJS Scan operator | Skipping previously accumulated valuesRXJS 扫描运算符的问题 |跳过以前累积的值
【发布时间】:2020-01-12 08:32:47
【问题描述】:

我有两个流。流 A 和 B。流 B 依赖于流 A,并且预计会随着时间的推移累积流 A 发出的值。我正在使用扫描运算符来实现这一点。但是,问题是 - 每当流 A 发出一个值时,流 B 中的扫描运算符总是以默认值而不是先前累积的值开始。所以我的输出总是基于当前的响应,一旦新值到达,我就会丢失这些值。

Stream A 基于我们的 UI。我有两个选项卡和一个输入表单,用户在其中提交帐户 ID。我需要选项卡名称和所选输入的值。 我不确定我在这方面缺少什么。如果有人有任何建议,将不胜感激。下面提供的代码

  private streamA$ = this.selectedTab$.pipe(
    switchMap((tab) =>
      this.accountSubmitted$.pipe(
        switchMap(({ account, type }) => {
          return this.myHttpService.method.pipe(
            map((response) => {
              return {
                type,
                response
              };
          })
        );
      })
    )
  ),
 share()
);

private streamB$ =  this.streamA$.pipe(
  map(({ type, response }) => {
    const { graph } = response;
    return { type, graph };
  }),
  scan((accResponse, currentResponse) => {
    const { type, graph: linkedDetails } = currentResponse;
    const { nodes: newNodes = [], edges: newEdges = [] } = linkedDetails;
    if (type === 'init') {
      return {
        nodes: newNodes,
        edges: newEdges
      };
    }

    const { nodes: linkedNodes = [], edges: linkedEdges = [] } = accResponse;
    const allNodes = [...linkedNodes, ...newNodes];
    const allEdges = [...linkedEdges, ...newEdges];
    return {
      nodes: allNodes,
      edges: allEdges
    };
  }, {})
 );

【问题讨论】:

  • 您能确认type 有时与“init”不同吗?否则,您的 accResponse 将始终被忽略
  • 可以初始化和更新。

标签: angular rxjs observable


【解决方案1】:

如果有人在寻找类似的问题,在我的情况下,问题不在流中。流按预期工作正常。主要问题是在 UI 中。我在 ngIf & else 块中有一个加载屏幕,每当新的 http 调用正在进行时,它就会显示加载屏幕,当我收到响应时,我的组件以及异步文件会显示。由于我的组件在每次 http 调用时都会从 UI 中破坏/删除,因此每次都会重新注册和订阅它。因此,累加器(先前累积的)响应始终是

{}

所以现在我更新了我的组件以始终显示,加载程序将根据 http 响应显示/隐藏。所以它不会每次都销毁和重新订阅。它订阅一次并且始终存在。现在,scan 保留了所有以前的值,并且代码按预期工作。

希望这对某人有所帮助。

快乐学习

瓦特萨尔

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    • 2016-11-06
    • 2022-01-17
    相关资源
    最近更新 更多