【问题标题】:How to better write Subscribe within Subscribe Angular?如何在订阅 Angular 中更好地编写订阅?
【发布时间】:2020-11-25 23:45:00
【问题描述】:

我有一个对话框,我订阅了它的 afterclosed() 方法,如果结果为真,我调用另一个服务并订阅它。

我不想在订阅中进行订阅。

写它的更好方法是什么?我想 Rxjs 运营商可以提供帮助,但如何以及为什么它更好?

dialog.afterClosed().subscribe((result) => {
      if (result) {
        this.projectService.deleteProject(name).subscribe(
          () => {
            this.getProjects();
          },
          (error) => {
            this.alertify.error(error);
          }
        );
      }
    });

【问题讨论】:

  • 使用 switchMap 可能吗? dialog.afterClosed().pipe(switchMap(name => this.getProjects())).subscribe()
  • 感谢您的评论,但您能否将代码清晰并解释一下。我是 Rxjs 新手,所以它会更有帮助。
  • mergeMap 似乎做了最少的假设。 switchMap 的语义似乎不适用

标签: angular typescript rxjs


【解决方案1】:

您可以使用 RxJS 高阶映射运算符switchMapconcatMapflatMap(又名mergeMap)或exhaustMap 之一。每个都有其特定的用例。你可以找到一篇好的文章here

我将使用switchMap 进行说明。如果来自第一个请求的 result 为 false/未定义,我也会返回 RxJS EMPTY 常量。它会发出一个complete 通知,而没有nexterror。所以this.getProjects()this.alertify.error(error)这两个函数都没有被触发。

import { EMPTY } from 'rxjs';
import { switchMap } from 'rxjs/operators';

dialog.afterClosed().pipe(
  switchMap(result => {
    if (result) {
      return this.projectService.deleteProject(name);
    }
    return EMPTY;                 // <-- complete without `next` or `error` notifications
  })
).subscribe(
  res => this.getProjects(),
  error => this.alertify.error(error)
);

【讨论】:

    猜你喜欢
    • 2018-05-13
    • 2020-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-24
    • 2020-11-16
    • 1970-01-01
    • 2019-11-04
    相关资源
    最近更新 更多