【问题标题】:Using rxjs to execute http call sequentially使用rxjs顺序执行http调用
【发布时间】:2022-02-22 00:31:08
【问题描述】:

我有这 4 个 api 调用

1. HttpService.PostAsync<any, any>(`post_update_ac_translates`)
2. HttpService.PostAsync<any, any>(`post_start_auto_ac_mapping`)
3. HttpService.PostAsync<any, any>(`get_std_leaf_ac_items`)
4. HttpService.PostAsync<any, any>(`get_all_ac_translates`)

我想按这个顺序执行它们

先执行1,完成时执行2,再执行2后,同时执行3和4。

我试着这样做:

concat(
    HttpService.PostAsync<any, any>(`post_update_ac_translates`, {p_id: this.props.projectId, ac_trans: data}, HttpService.AuditcoreAPIBasePath),
    HttpService.PostAsync<any, any>(`post_start_auto_ac_mapping`, {p_id: this.props.projectId}, HttpService.AuditcoreAPIBasePath)
).subscribe(() => {
    forkJoin(
        HttpService.GetAsync<any, any>(`get_std_leaf_ac_items`, {p_id: this.props.projectId}, HttpService.AuditcoreAPIBasePath),
        HttpService.GetAsync<any, any>(`get_all_ac_translates`, {p_id: this.props.projectId}, HttpService.AuditcoreAPIBasePath)
    ).subscribe(([resp1, resp2]) => {

但是正在执行的代码有后续

1 => 3/4 => 2 => 3/4

而不是

1=> 2 => 3/4

在做

HttpService.PostAsync&lt;any, any&gt;(`post_update_ac_translates`, {p_id: this.props.projectId, ac_trans: data}, HttpService.AuditcoreAPIBasePath).concat(

返回错误

类型上不存在属性“concat” 'AxiosObservable'.ts(2339)

【问题讨论】:

    标签: rxjs observable


    【解决方案1】:

    我建议不要嵌套 subscribe() 调用,而是建议使用以下链接 RxJS 可管道运算符的方法,因为它可能看起来更简洁。

    HttpService.PostAsync<any, any>(`post_update_ac_translates`)
      .pipe(
        switchMap(() => HttpService.PostAsync<any, any>(`post_start_auto_ac_mapping`))
        switchMap(() => forkJoin(HttpService.PostAsync<any, any>(`get_std_leaf_ac_items`), HttpService.PostAsync<any, any>(`get_all_ac_translates`))
      ).subscribe([res1, res2] => {
         console.log(res1);
         // do the rest
      });
    

    首先,我们使用switchMap() 将来自第一个 HTTP 请求的 observable 值映射到一个内部 observable,然后发出第二个 HTTP 请求。然后,我们链接另一个 switchMap() 操作符,它将执行 forkJoin 操作,等待第三个和第四个 HTTP 请求完成,然后我们订阅并从 observable 返回值。

    【讨论】:

    • 谢谢,看起来不错,我只是想知道是否有可能从 3/4(所以你的最后一个 switchmap)获得响应并使用这些响应执行代码?会是subscribe([resp1,resp2,resp3,resp4])
    • 我试过 subscribe(([resp1, resp2, [resp3, resp4]]) 但我得到了 > 长度为 '2' 的元组类型 '[AxiosResponse, AxiosResponse]' 在索引 '2' 处没有元素
    • @Bobby 是的,你可以!检查我编辑的答案。通过这样做,您将能够获得来自第 3 和第 4 个 HTTP 请求的响应
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-19
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 2021-07-12
    • 2020-03-26
    • 2020-02-26
    相关资源
    最近更新 更多