Jon Sud
Jon Sud

Reputation: 11641

How to filter entities in ngrx?

I created a ngrx entity service:

@Injectable({ providedIn: 'root' })
export class ProductsDataService extends EntityCollectionServiceBase<{ id, name, isActive }> {
  actives$ = this.entities$.pipe(filter(e => e.isActive); <------ but e is an Array!

I want to filter by isActive === true.

But the problem I get e as array.. so I can't do filter.

I can do .pipe(map(e => e.filter(ee => ee.isActive))) but this solution is not feel right because it takes two operations in one method (map).

Any idea how to do it by ngrx/rxjs way?

Upvotes: 0

Views: 1025

Answers (1)

Jensen
Jensen

Reputation: 6646

Your map function is the correct way to do it:

 this.entities$.pipe(map(e => e.filter(...));

Filter is here to filter the data stream but not to filter the data itself, i.e. Emit values that pass the provided condition (reference: learnrxjs.io/learn-rxjs/operators/filtering/filter). In other words deciding whether the data flow should work for specific condition only.

A quick example:

x.pipe(filter(num => num === 2)).subscribe(val => console.log(val))

will print only when 2 is emitted from x.

Upvotes: 1

Related Questions