I have replaced this.userrights
to userrights$
observable:
public userrights$: Observable<UserRight[]>;
Before was a filter method is called from template by click event:
filterState(state: UserRightState) {
this.userrights = this.clonned.filter((st: UserRight) => (this.filterBy == state ? true : st.value === getRightStateValue(state)));
this.filterBy = this.filterBy == state ? null : state;
}
How to rewrite it on RXJS?
I have createed a new subject that contains filter state public state$ = new Subject<UserRightState >()
.
How to filter BehaviorSubject data and return back?
CodePudding user response:
If you have both filterBy and the list you want to filter in two Observables you can use combineLatest()
:
filterBy$ = new BehaviorSubject<UserRightState | null>(null);
allUserRights$ = new BehaviorSubject<UserRight[]>([]);
userrights$ = combineLatest([
filterBy$.pipe(
pairwise(),
map(([prevState, state]) => prevState === state ? null : state),
), // This will take care of toggling filterBy.
allUserRights$,
]).pipe(
map(([filterBy, userRights]) => userRights.filter(/* do whatever with `filterBy` */))
)
filterState(state: UserRightState) {
filterBy$.next(state);
}
If you know that this.clonned
will never change you can remove combineLatest
of course.
CodePudding user response:
You can map
the observable to another observable:
const filteredRights$ = userrights$.pipe(
map(rights => rights.filter(rights => // whatever condition))
);