Angular 9 pipe transform array using filter with a filter function that returns an observable

Mikkel

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.

Kurt Hamilton

You want to:

  • get an Observable<boolean> for some unknown number of input values
  • filter the input values based on the observable value responses

I would:

  1. Set up the observables as one array
  2. Run them in parallel in a forkJoin
  3. Use 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))
  );
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related