代码之家  ›  专栏  ›  技术社区  ›  ViqMontana

RxJS-链接多个可观察对象并在其间执行其他操作

  •  0
  • ViqMontana  · 技术社区  · 6 年前

    我在网上找了很多东西,却找不到任何能描述我问题的东西。

    我现在用的是Angular 5。

    基本上,我想表演一个 put http请求,然后在完成后执行一些操作,然后执行另一个 get

    下面是我使用嵌套订阅的代码(我知道您不应该这样做):

    this.projectService.updateProject(this.project).subscribe(
      subscribe => {
        doSomethingAfterTheUpdate();
        this.projectService.get(this.id).subscribe(
          subscribe => {
            doSomethingAfterTheGet();
            });
        });
    

    如您所见,我正在更新项目,然后获取项目。如何使用RxJS正确地实现这一点。我已经研究了Concat和MergeMap方法,但是我想在更新和get之后执行一些操作。

    2 回复  |  直到 6 年前
        1
  •  1
  •   Jota.Toledo    6 年前

    doSomethingAfterTheUpdate

    import { mergeMap, tap } from 'rxjs/operators';
    
    this.projectService.updateProject(this.project).pipe(
       tap(_ => this.doSomethingAfterTheUpdate()),
       mergeMap(_ => this.projectService.get(this.id))
    ).subscribe(_ => this.doSomethingAfterTheGet());
    

    _ 在某些管道操作上,因为您实际上不使用范围值。

        2
  •  2
  •   Alexander Staroselsky    6 年前

    您应该能够使用运算符 tap switchMap 要实现这一点:

    import { switchMap, tap } from 'rxjs/operators';
    
    // ...
    
    this.projectService.updateProject(this.project)
      .pipe(
        tap(() => doSomethingAfterTheUpdate()),
        switchMap(() => this.projectService.get(this.id)),
        tap(() => doSomethingAfterTheGet())
      )
      .subscribe(results => console.log(results));