代码之家  ›  专栏  ›  技术社区  ›  Deniss M.

RxJs:一个接一个地执行3个观察结果,并使用第三个请求中的第一个和第二个请求的结果

  •  1
  • Deniss M.  · 技术社区  · 7 年前

    我需要能够执行3个观察一个接一个,以便我可以使用结果值从第一个在第二,也第一和第二个结果在第三个。

    像这样的东西( 它不起作用,因为serviceId在第三个请求中不可见 ):

    private setupStuff(): void {
            this.initRouteParams().pipe(
                switchMap(serviceId => this.getFileInfo(serviceId)),
                switchMap(fileName => this.getExistingFile(serviceId, fileName)
                    .subscribe(response => {
                        console.log(response);
                    }))
                );
        }
    
    3 回复  |  直到 7 年前
        1
  •  5
  •   Hikmat G.    7 年前

    您可以显式地将serviceN的值返回到serviceN+1。我的想法是:

    private setupStuff() {
      this.initRouteParams()
        .pipe(
          switchMap(serviceId => {
            return zip(of(serviceId), this.getFileInfo(serviceId))
          }),
          switchMap(([serviceId, filename]) => {
            return zip(of(serviceId), of(filename), this.getExistingFile(serviceId, filename))
          })
        )
        .subscribe(([serviceId, filename, response]) => {
          console.log(serviceId, filename, response);
        })
    }
    

    编辑:

    可以通过显式声明每个输入的类型来修复类型错误。您可能希望为 response .

        2
  •  0
  •   Deniss M.    7 年前

    成功地解决了这个问题:

    private checkFilePresence(): void {
            const first$: Observable<string> = this.initRouteParams();
            const second$: Observable<string> = first$.pipe(
                switchMap(config => {
                    return this.getFileInfo(config);
                })
            );
            const third$: Observable<CkitExistingFileResponse> = combineLatest(first$, second$).pipe(
                switchMap(([config, second]) => {
                    return this.getExistingFile(config, second);
                })
            );
            combineLatest(first$, third$)
                .subscribe(() => {
                });
        }
    
        3
  •  -1
  •   byj    7 年前

    您可以按如下顺序对可观测数据进行订阅:

    private setupStuff(): void {
            this.initRouteParams().subscribe( serviceId => {
                this.getFileInfo(serviceId).subscribe(fileName => {
                   this.getExistingFile(serviceId, fileName).subscribe( response => {
                       console.log(response);
                    });
                });
            });
    }