如何在rxJs订阅中链接API调用并使用Angular进行映射?

问题描述 投票:0回答:1

我正在执行多个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上是成功的,我不知道为什么呼叫没有发送。

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

我尝试过使用.pipe然后使用.map,但这也无效。

调试代码时,它会在两个调用中导航,第二个.map(result => result)包含从response => response返回的相同id。

这让我觉得我只能在取消订阅之前进行一次API调用,任何人都可以对此进行任何澄清。

javascript angular rxjs
1个回答
1
投票

第二个流没有订阅。

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

this.http.post(/* args here */)
  .pipe(
    switchMap(result => {
      /* do something with result */
      return this.http.post(/* args here */)
    })
  ).subscribe( /* subscriber here */)
© www.soinside.com 2019 - 2024. All rights reserved.