小编Хри*_*тов的帖子

如果我有combineLatest,那么使用 ngrx 和 rxjs 选择有什么不同?

我有产品服务,我想从州获得最好的产品。

我可以实现此目的的一种方法是使用rxjs如下所示:

 @Injectable({ providedIn: 'root' })
 export class ProductDataService extends EntityCollectionServiceBase<Product> {
  
    bestProductsIds$ = new BehaviorSubject([]);

    bestProducts$ = combineLatest([this.entities$, this.bestProductsIds$]).pipe(
      map(([products, ids]) => products.filter((p) => ids.includes(p.id))),
      map((products) => orderBy(product, ['createdDate', ['desc']])),
      map((products) => this.toProductCard(products))
    );
}
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用选择器:

export const selectBestProducts = createSelector(
  ([products, ids]) => products.filter((p) => ids.includes(p.id)),
  (products) => orderBy(products, ['createdDate', ['desc']])
);


@Injectable({ providedIn: 'root' })
export class ProductDataService extends EntityCollectionServiceBase<Product> {

  bestProductsIds$ = new BehaviorSubject([]);

  bestProducts$ = combineLatest([this.entities$, this.bestProductsIds$]).pipe(select(selectBestProducts));

  ...
}
Run Code Online (Sandbox Code Playgroud)

我知道 ngrx 选择器是记忆函数,但我在这里使用combineLatest …

rxjs ngrx angular

5
推荐指数
1
解决办法
328
查看次数

标签 统计

angular ×1

ngrx ×1

rxjs ×1