简体   繁体   English

rxjs - 基于具有初始值的 Observable 的 startWith

[英]rxjs - startWith based on Observable with initial value

I have a data source with query, sort and pagination features.我有一个具有查询、排序和分页功能的数据源。 All of these are defined as BehaviourSubjects.所有这些都被定义为 BehaviourSubjects。 I am trying to implement state saving the of the table, restoring the query, sort and pagination values.我正在尝试实现保存表的状态,恢复查询、排序和分页值。

Currently I have the code below that is responsible for it:目前我有下面的代码负责它:

// params restored from storage
const pageSize = this.params.page?.pageSize ?? 20;
this.pageIndex = this.params.page?.pageIndex ?? 0;

query = new BehaviorSubject<Q | undefined>(params.query);
sort = new BehaviorSubject<Sort<T> | undefined>(params.sort);
page = new Subject<PageEvent>();

Code that manages data query:管理数据查询的代码:

combineLatest([this.query, this.sort])
.pipe(
  switchMap(([query, sort]) => this.page.pipe(
    // combine pageIndex: 0 for query, sort change
    startWith({ pageIndex: this.pageIndex, pageSize } as PageEvent), 
    map(page => [
      this.storeParams({ query, sort, page }),
      this.store.dispatch(
        this.selectAction({ query, page: page.pageIndex, sort, size: page.pageSize })
      )
    ]),
    catchError(error => of()),
  ))
);

It works properly but when sort or query values change, I need to reset pageIndex to 0. If I use startWith with pageIndex equal to 0, then I loose the ability to restore page values from storage.它工作正常,但是当排序或查询值更改时,我需要将 pageIndex 重置为 0。如果我使用 startWith 且 pageIndex 等于 0,那么我将失去从存储中恢复页面值的能力。

To achieve it I reset the pageIndex on sort and query functions:为了实现它,我在排序和查询函数上重置了 pageIndex:

sortBy(sort: Sort<T>): void {
  this.pageIndex = 0; // need to remove
  this.sort.next(sort);
}

queryBy(query: Partial<Q>): void {
  this.pageIndex = 0; // need to remove
  this.query.next(query as Q);
}

How is it possible to achive this using a single operator, ie the combineLatest above?如何使用单个运算符(即上面的 combineLatest )实现这一目标?

Does something like this work?这样的东西有用吗? Just reset pageIndex every time combineLatest([this.query, this.sort]) has a new value.每次combineLatest([this.query, this.sort])有新值时只需重置 pageIndex。

combineLatest([this.query, this.sort]).pipe(
  tap(_ => this.pageIndex = 0),
  switchMap(([query, sort]) => this.page.pipe(
    // combine pageIndex: 0 for query, sort change
    startWith({ pageIndex: this.pageIndex, pageSize } as PageEvent), 
    map(page => [
      this.storeParams({ query, sort, page }),
      this.store.dispatch(
        this.selectAction({ 
          query, 
          page: page.pageIndex, 
          sort, 
          size: page.pageSize 
        })
      )
    ]),
    catchError(error => of()),
  ))
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM