0

I have an Angular material menu with sub-menu panels. It's in a file manager app, and there is a context menu for the files, which has an option to "Move to" a folder:

enter image description here

I an trying to make clicking a middle level panel also close the entire menu (this is not the default behavior).

To do that, i wrote this function:

 private handleClosingOptionsMenuWhenMovingFiles() {
    this.actionsMenuOpened$.pipe(
      untilComponentDestroyed(this)
    ).subscribe(() => {
      this.documentsTabDetailsService.moveToFolderEvent$.pipe(
        takeUntil(this.contextMenuTrigger.menuClosed),
      ).subscribe(
        () => this.contextMenuTrigger.closeMenu(),
        () => { },
        () => console.log(' COMPLETED'));
    });
  }

It works great, but it's using ugly nested subscribes, and i can't figure out how to convert it to a single pipe with operators, and only one subscribe at the end.

The issue is that the actionsMenuOpened$ should still be subscribed to, because the user may open the menu again, but the inner stream of moveToFolderEvent$ should complete each time the menu is closed.

Any idea?

RoiTr
  • 136
  • 11
  • 1
    you can make use of rxjs operators like `switchMap`. I have an example at this post :) https://stackoverflow.com/a/55447947/10959940 – wentjun May 17 '20 at 10:07

2 Answers2

1

please use flatmap along with pipe, try this

this.actionsMenuOpened(...)
  .pipe(
    flatMap(success => this.documentsTabDetailsService.moveToFolderEvent(...)),
  )
  .subscribe(success => {(...)}); 

please check more details about flatmap here http://reactivex.io/documentation/operators.html

Shlok Nangia
  • 2,355
  • 3
  • 16
  • 24
  • Thanks! I changed it to: `this.actionsMenuOpened$.pipe( untilComponentDestroyed(this), flatMap(() => this.documentsTabDetailsService.moveToFolderEvent$), takeUntil(this.contextMenuTrigger.menuClosed), ).subscribe( () => this.contextMenuTrigger.closeMenu(), () => { }, () => console.log(' COMPLETED') );` but i never see the COMPLETED log when navigating to another page. Am i doing something wrong? – RoiTr May 17 '20 at 10:09
0

I finally decided to go with another approach:

    this.documentsTabDetailsService.moveToFolderEvent$.pipe(
      untilComponentDestroyed(this))
      .subscribe(
        () => {
          if (this.contextMenuTrigger.menuOpen) {
            this.contextMenuTrigger.closeMenu();
          }
        }, err => { },
        () => console.log('COMPLETED')
      );

It subscribes, and stays subscribed, to the event that fires when moving an item. I am not sure if which is better in terms of performance (maybe i'm now keeping an open subscription for longer).

RoiTr
  • 136
  • 11