Reputation: 196
I have tried searching for a way to filter an array using a function that returns an observable boolean.
What I need is a pipe that filters values based on a users permissions, and given the fact that permissions are an observable I can't assume they are present when the page loads.
I want this to happen in a pipe, because this might be reused later.
So in a naive way what I want to do is:
Called using
*ngFor="let value of values | selector"
Pipe:
... ...
@Pipe({
name: 'selector',
pure: false
})
... ...
transform(value: { value, viewValue, permission: AuthGroup }[]): Observable<any[]> {
return value.filter(o => this.authorizationService.hasPermission(o.permission).subscribe(s => s));
}
Where this.authorizationService.hasPermission
returns an Observable<boolean>
But I have not been able to find anything detailing if it is at all possible.
I realize that it is bad having the .subscribe
in there, it is just to indicate my intention.
I have tried a lot of different things, but I think either it is not possible or I am just not familiar with the syntax of RXJS to make it work correctly.
Edit:
In case others comes a across this and use Kurts answer, you would have to add | async
pipe like this:
*ngFor="let value of values | selector | async"
because the pipe returns an oberservable, I didn't include in the original question because I wanted my completely naive thought to be the question.
Upvotes: 0
Views: 1792
Reputation: 13515
You want to:
Observable<boolean>
for some unknown number of input valuesI would:
forkJoin
map
to filter the input array based on the returned boolean values@Pipe({
name: 'selector',
pure: false
})
transform(value: { value, viewValue, permission: AuthGroup }[]): Observable<any[]> {
// 1. set up the observables
const permissionObservables: Observable<boolean>[] = value
.map(o => this.authorizationService.hasPermission(o.permission));
// 2. run in parallel
return forkJoin(permissionObservables).pipe(
// 3. return value filtered by results of observables
map((permissions: boolean[]) => value.filter((x, i) => permissions[i] === true))
);
}
Upvotes: 1