【问题标题】:How to get previous value of RxJS Subject?如何获取 RxJS 主题的先前值?
【发布时间】:2020-11-13 05:24:06
【问题描述】:

在我的项目中,我需要将分页器的 pageSize 值(每页的项目数)与之前的值进行比较,如果新的值更高,那么我需要从存储中加载数据。但如果它不更高,我什么都不想做。

例如在这段代码中:

export class MyComponent {
  paginatorPageSize: BehaviorSubject<number> = new BehaviorSubject<number>(10);
  // ...

  savePageSettings() {
    this.pageService.save().pipe(
      map((result: any) => {
        // ...
      }),
      tap(() => this.anyCode.here()),
      switchMap((result: any) => {
        // ...
      }),
      switchMap(() => {
        const previousPageSize = ??? // <--- here how can I get the prevoius value of paginatorPageSize?

        if (previousPageSize >= this.paginatorPageSize.value) {
          return this.pageService.getAll();
        }

        return of(null)
      })
    ).subscribe();
  }
}

有什么方法可以获取 RxJS Subject / BehavioSubject 或任何类型的主题的先前发出的值?

【问题讨论】:

  • 你需要pairwise运营商

标签: typescript rxjs rxjs6


【解决方案1】:

只需使用pairwise 运算符。

savePageSettings() {
    this.pageService.save().pipe(
      map((result: any) => {
        // ...
      }),
      tap(() => this.anyCode.here()),
      switchMap((result: any) => {
        // ...
      }),
      pairwise(),
      switchMap(([oldResult, newResult]) => {
        const previousPageSize = oldResult.pageSize;

        if (previousPageSize >= this.paginatorPageSize.value) {
          return this.pageService.getAll();
        }

        return of(null)
      })
    ).subscribe();
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多