using filter operator with pipe - conditionally

Viewed 289

i cant move the filter operator outside the map with a condition

return this.http.get('profili/usermenu')
                    .pipe(
                        map((menu: Menu[]) => {

                            if (this.appConfig.config.DisableRitiriDetails)
                                menu = menu.filter(item => !item.Description.includes('xxx'));
                            
                            const menuCreated: SidenavItem[] = this.menuSrv.populateMenu(menu); 
                            this.router.navigate([menuCreated[0].routeOrFunction]);
                            return new MenuSuccess(menuCreated);
                        }),
                        catchError(() => of(new LoginError(3)))
                    );

something like

return this.http.get('profili/usermenu')
                    .pipe(
                        filter((menu: Menu) => this.appConfig.config.DisableRitiriDetails || !menu.Description.includes('xxx')),
                        map((menu: Menu[]) => {
                            
                            const menuCreated: SidenavItem[] = this.menuSrv.populateMenu(menu); 
                            this.router.navigate([menuCreated[0].routeOrFunction]);
                            return new MenuSuccess(menuCreated);
                        }),
                        catchError(() => of(new LoginError(3)))
                    );

in this way it gives me error to the map((menu: Menu[])

1 Answers

The operator filter is:

A function that evaluates each value emitted by the source Observable.

It is whole array, Menu[], not individuals items of the array. Return value is expected to be truthy/falsy.

Your intention is filter the items of the array, so you need another map function, see pruneMenuItems (I am not sure how to name function better as the original condition is confusing):

const pruneMenuItems = (menu: Menu[]) => this.appConfig.config.DisableRitiriDetails
      ? menu
      : menu.filter(item => !item.Description.includes('xxx'))

return this.http.get('profili/usermenu')
  .pipe(
    map(pruneMenuItems),
    map((menu: Menu[]) => {
      const menuCreated: SidenavItem[] = this.menuSrv.populateMenu(menu); 
      this.router.navigate([menuCreated[0].routeOrFunction]);
      return new MenuSuccess(menuCreated);
    }),
    catchError(() => of(new LoginError(3)))
  );
Related