如何用mergeMap或switchMap替换订阅?

时间:2020-04-23 09:49:32

标签: angular rxjs

我想用switchMap代替subscribe中的subscribe,我不知道该怎么做。我需要一个例子,但是我没有在互联网上找到它。

dialogRef.afterClosed().pipe(filter(result => !!result)).subscribe(result => {
            result.owner = this.user.id;
            proj._newname = result.name;
            proj.name = result.name;
            this.projectService.updateProject(proj, result.name)
                .subscribe(project => {
                        const pw = new ProjectWorker({
                            approve: true,
                            worker: this.user.id,
                            project: project.id,
                            admin: true,
                            write: true
                        });
                        this.projectService.createProjectWorker(pw).subscribe(_ => {
                            this.getProjects();
                        });
                    },
                    err => {
                        this._snackbar.open('Project already exist', 'error', {
                            panelClass: 'snackbar-error'
                        })
                    });
            }
        );

1 个答案:

答案 0 :(得分:1)

类似这样的东西:

dialogRef.afterClosed().pipe(
  filter(result => !!result),
  switchMap((result) => {
    result.owner = this.user.id;
    proj._newname = result.name;
    proj.name = result.name;
    return this.projectService.updateProject(proj, result.name);
  }),
  switchMap((project) => {
    const pw = new ProjectWorker({
      approve: true,
      worker: this.user.id,
      project: project.id,
      admin: true,
      write: true
    });
    return this.projectService.createProjectWorker(pw);
  }),
).subscribe(
  res => this.getProjects(),
  err =>
    this._snackbar.open('Project already exist', 'error', {
      panelClass: 'snackbar-error'
    })
);
相关问题