【问题标题】:Merging incremental data into full data将增量数据合并为完整数据
【发布时间】:2021-02-13 08:45:51
【问题描述】:

我的 Angular 组件在 ngOnInit() 方法中从服务器加载完整数据:

ngOnInit(): void {
  this.data$ = this.getInitialData();
}

getInitialData(): Observable<Player[]> {
  return of([
    {
       name: "Test Player 1",
       matches: 0
    },
    {
      name: "Test Player 2",
      matches: 0
    }
  ]);
}

此方法将结果 Observable 设置在变量 data$ 上。 该变量将在 HTML 模板中用于与异步管道交互以实际订阅完整的数据加载。

<div *ngFor="let a of data$ | async">
  <span>{{a.name}}</span>
  <span>{{a.matches}}</span>
</div>
    
<button (click)="refresh()">refresh</button>

此外,HTML 模板中存在一个刷新按钮,它会生成另一个 Web 服务请求。此 Web 服务不会再次加载完整数据,而是仅响应增量更改。

refresh(): void {
  console.log("refresh button clicked");
  // TODO: when clicking the refresh button, the result of
  // getDiffData() should be merged into the result of the
  // initial getInitialData() and then be returned into the template via data$ | async
}

private requests = 0;

getDiffData() {
  return of([
    {
      name: "Test Player 2",
      matches: ++this.requests
    }
  ]);
}

我不知道如何仅使用 rxjs-way 将增量数据合并为完整数据。

我可以通过在 component.ts 文件中订阅的方式将所有数据合并在一起(进一步将合并后的数据设置在 Subject 中并在模板中订阅它),但必须有一个 RXJS 模式,我可以用它吗?

我的代码的实际外观:https://stackblitz.com/edit/angular-hec61p-vgjyew?file=src%2Fapp%2Fapp-component.ts

【问题讨论】:

  • 我们可以假设name 对您的商品来说是独一无二的吗?我的意思是我们可以通过名称字段在现有数组中找到项目?
  • 您是否在问如何将新数组合并到现有数组中,考虑到名称可能重叠,所有这些都使用 rxjs?或者只是如何使用 async 管道“收听”一次 Observable 并优雅地获取更新?
  • 我宁愿询问正确的“合并 2 个数组”逻辑。我可以假设您实现了mergeDataAndDiffArrays(data, diff) 之类的东西吗?
  • 我不认为实际的合并是 rxjs 的挑战。但我可能错了。
  • 我明白了。但不同的人会问关于 SO 的问题。这也可能是对某人的挑战

标签: angular


【解决方案1】:

我建议使用 update$ 作为主题 = 刷新点击的来源和扫描运算符来合并数据

this.data$ =  concat(
      this.getInitialData(),
      this.update$.pipe(
        switchMap(() => this.getDiffData())
      )
    ).pipe( 
      scan((oldData, updateData) => mergeUpdates(oldData, updateData)), // could be [...oldData, ...updateData]
    );

【讨论】:

    猜你喜欢
    • 2022-01-20
    • 2021-10-16
    • 2012-09-18
    • 2021-09-11
    • 1970-01-01
    • 1970-01-01
    • 2018-06-12
    • 1970-01-01
    • 2020-04-27
    相关资源
    最近更新 更多