多个同时 POST 请求,如果其中一个失败则不发送任何请求

乔乔福克

所以我想一起发送 2 个 post 请求,但我想要它,以便如果 2 个请求中的任何一个失败(例如意外错误),实际上没有一个请求通过。这是假设 2 个 post 请求在后端是单独的功能(即:2 个单独的端点)。

我搜索并发现了一些相对相似的问题,但是如果一个请求失败,所有解决方案都不会取消这两个请求,而且其中很多都使用了似乎已弃用的函数 ( mergeMap, forJoin, ...)

试图

我尝试了多种选择:

在另一个请求中映射一个请求:

this.service.postFunction1(body1).pipe(
  map(()=>this.service.postFunction2(body2).subscribe(
    res=>{
      /** Stuff here... **/
    },
    err=>{
      /** Stuff here... **/   //Should I stop here the whole thing here?
    })
  )
).subscribe(
  res=>{
    /** Stuff here... **/
  },
  err=>{
    /** Stuff here... **/
  })
)

嵌套订阅:

(我知道这不是一个好习惯)

this.service.postFunction1(body1).subscribe(
  res=>{
    this.service.postFunction2(body2).subscribe(
     res=>{},
     err=>{}
    )
  },
  err=>{
    /** Stuff here... **/   //Should I stop here the whole thing here?
  })
)

现在我将它们完全分开,因为我没有清楚地知道如何将它们组合在一起,牢记“如果一个失败,他们都失败”。

也许我只需要修改后端并将 2 个 post 请求作为一个函数(1 个端点)处理,但我很好奇是否有办法用单独的请求来做到这一点。

阿西什·兰詹

您可以为此使用cancatMap()如果您可以将 API url 排列在数组中,并按要调用 API 的顺序排列,那么您可以使用以下内容:

// consider these as API urls
urls = ['url1', 'url2', 'url3']

from(this.urls).pipe(
  concatMap((eachUrl, index) => {
    if (index === 1) {
      return throwError('Error in Second') // simulated error thrown by second API call
    }
    // simulated API calls, you just need to return this, not the error simulation
    // return your API call here and that's all under your concatMap()
    return of(eachUrl).pipe(tap(_ => console.log('API url invoked -> ', eachUrl)))
  })
).subscribe((data) => {
  console.log(`data in subscribe `, data);
}, (err) => {
  console.log(`error in subscribe: `, err)
})

您将看到第三个 API 调用不会触发。

concatMap() 将在发送下一个请求之前等待请求完成。

在此处查看示例:https : //stackblitz.com/edit/angular-qo1luf?file=src/app/app.component.ts

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章