当您不希望外部订阅完成而内部订阅应该完成时,请避免嵌套订阅

时间:2020-05-17 09:44:42

标签: angular rxjs

我有一个带有子菜单面板的Angular材质菜单。 它在文件管理器应用程序中,并且具有文件的上下文菜单,该菜单具有“移至”文件夹的选项:

enter image description here

我试图单击中级面板也会关闭整个菜单(这不是默认行为)。

为此,我编写了以下函数:

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

它很好用,但是它使用了丑陋的嵌套订阅,而且我不知道如何使用运算符将​​其转换为单个管道,最后只有一个订阅。

问题在于,由于用户可能会再次打开菜单,所以仍应订阅actionsMenuOpened $,但是moveToFolderEvent $的内部流应在每次关闭菜单时完成。

有什么主意吗?

2 个答案:

答案 0 :(得分:1)

请与flatmap一起使用pipe,请尝试

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

请在http://reactivex.io/documentation/operators.html此处查看有关flatmap的更多详细信息

答案 1 :(得分:0)

我最终决定采用另一种方法:

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

它订阅并保持订阅,以移动项目时触发的事件。 我不确定在性能方面哪个更好(也许我现在保留开放订阅的时间更长)。

相关问题