我有产品服务,我想从州获得最好的产品。
我可以实现此目的的一种方法是使用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 …