【问题标题】:How to chain API calls in rxJs subscribe and map with Angular?如何在 rxJs 订阅和映射中使用 Angular 链接 API 调用?
【发布时间】:2019-04-20 21:57:08
【问题描述】:

我正在执行多个 API 调用。一个创建用户,第二个创建团队。

用户创建返回一个UserId,然后将其用作团队创建的一部分。

我在 Angular 中使用 rxjs 库,使用 .map 和 .subscribe 方法等待第一个调用解决,然后将 UserId 传递给第二个 api 调用。

第一个电话正在解析并返回我需要的UserId,但第二个电话甚至没有发送。

    this.http.post<number>(this.baseUrl + 'api/register/', UserTeam, {
      headers: new HttpHeaders({
        "Content-Type": "application/json"
      })
    })
      .map(response => response)
      .subscribe(result =>
      //result = the new user id from registering new user
      {
        var newTeam = JSON.parse(UserTeam);
        newTeam.userId = result;
        newTeam = JSON.stringify(newTeam);
        this.http.post(this.baseUrl + 'api/team/', newTeam, {
          headers: new HttpHeaders({
            "Content-Type": "application/json"
          })
        }).map(result => result)
      })

我已经调试过,当 URL 构建完成时,它应该会到达我的端点,并且在邮递员上测试时,我用它发送的正文在 URL 上是成功的,我不确定为什么调用是t 发送。

在我看来,它应该进行第二次 API 调用。

我尝试使用.pipe,然后使用.map,但这也不起作用。

在调试代码时,它会浏览两个调用,第二个 .map(result =&gt; result) 包含从 response =&gt; response 返回的相同 id。

这让我觉得在退订之前我只能进行一次 API 调用,任何人都可以提供任何明确的说明。

【问题讨论】:

标签: javascript angular rxjs


【解决方案1】:

第二个流没有被订阅。

使用当前的 RxJS 语法,它应该或多或少像这样

this.http.post(/* args here */)
  .pipe(
    switchMap(result => {
      /* do something with result */
      return this.http.post(/* args here */)
    })
  ).subscribe( /* subscriber here */)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-19
    • 1970-01-01
    • 1970-01-01
    • 2020-02-14
    相关资源
    最近更新 更多