RxJs:一个接一个地执行 3 个 observable,并在第二个请求中使用第一个结果,在第三个请求中使用第一个和第二个结果 [英] RxJs: Executing 3 observables one after another and using results from first in second, and first and second in third requests

查看:52
本文介绍了RxJs:一个接一个地执行 3 个 observable,并在第二个请求中使用第一个结果,在第三个请求中使用第一个和第二个结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要能够一个接一个地执行 3 个 observable,以便我可以在第二个中使用第一个的结果值,在第三个中使用第一个和第二个结果.

I need to be able to execute 3 observables one after another so that I can use result value from 1st one in second and also 1st and 2nd result in the third one.

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

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

推荐答案

您可以将 serviceN 的值显式返回给 serviceN+1.这是想法:

You can explicitly return the value of the serviceN to the serviceN+1. Here's the idea :

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 分配适当的类型.

You can fix types errors by explicitly declare types of each input. You probably want to assign the appropriate type for response.

这篇关于RxJs:一个接一个地执行 3 个 observable,并在第二个请求中使用第一个结果,在第三个请求中使用第一个和第二个结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆