Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
319 views
in Technique[技术] by (71.8m points)

angular - RxJs: Filter array with inner observable

I have an array of routes, which I'm trying to filter on depending if the service says the user has permission. I've tried various combination & transformative operators with no success mergeMap, concatMap, concatAll, mergeAll. The problem is that hasRoutePermission returns an observable that returns a boolean from the endpoint. Thanks in advance.

stackblitz

const exampleRoutes = [{
  model: 'ExampleModel'
}, {
  model: 'ExampleModel'
}, {
  model: 'ExampleModel'
}, {
  model: 'ExampleModel'
}];

filterRoutes(routes): Observable <[]> {
  const hasRoutePermission = (route: IRouteData): Observable <boolean> =>
    this.examplePermissionService.hasRoutePermission(route);

  return of(items)
  .pipe(
    filter(item => hasRoutePermission(item))// Problem is here
  )
}

I'm using an async pipe to subscribe to the filtered list in the template.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

So you receive boolean value inside Observable and now need to use one of "flattening" operators (like mergeMap, concatMap, etc) to get back primitive value:

const { of, from } = rxjs; // = require("rxjs")
const { mergeMap, filter, map, toArray } = rxjs.operators; // = require("rxjs/operators")

function hasRoutePermission(id) {
  return of(id % 2 === 0); // mock api logic
}

function filterRoutes(items) {
  return from(items).pipe(
    mergeMap(item =>
      hasRoutePermission(item).pipe(
        filter(permission => permission),
        map(() => item)
      )
    ),
    toArray()
  );
}

const filtered$ = filterRoutes([0,1,2,3,4,5]);
filtered$.subscribe(v => console.log(v));
<script src="https://unpkg.com/[email protected]/bundles/rxjs.umd.min.js"></script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...