【问题标题】:Build pipes with multiple async HTTP requests使用多个异步 HTTP 请求构建管道
【发布时间】:2019-05-28 07:39:06
【问题描述】:

我需要发出第一个 HTTP 请求并从对象的响应数组中获取。 然后我需要对数组中的每个对象(可能在循环中)发出 HTTP 请求以获取额外的信息。所有这些都在 Angular 中。我尝试使用管道,但遇到了一些困难。

【问题讨论】:

  • 什么“困难”?给minimal reproducible example
  • 我能够构建这个:this.homeworld = this.http.get('/api/people/1').pipe( mergeMap(character => this.http.get(character.家园)));从这里: this.http.get('/api/people/1').subscribe(character => { this.http.get(character.homeworld).subscribe(homeworld => { character.homeworld = homeworld; this.已加载字符 = 字符;});});
  • Edit 问题。这似乎对数组没有任何作用。

标签: angular rxjs angular-httpclient


【解决方案1】:

基本上,您可以通过将值拉出内部 Observable 并将其传递回父流来使用 mergeMap/flatMap 进行嵌套 api 调用。

就像下面答案中的示例一样,如果您必须进行嵌套调用以获取用户和他的偏好,您将使用如下所示的平面图。

ngOnInit() {
    this.userService.getUser().pipe(
        tap(u => this.user = u),
        flatMap(u => this.userService.getPreferences(u.username))
      ).subscribe(p => this.preferences = p);
}

How to make nested Observable calls in Angular2

【讨论】:

    【解决方案2】:

    您的解释很模糊,没有伪代码示例或您尝试做的实际示例,这很难回答。

    但我收集到的是你需要:

    API 调用 1:

    { ids: [1, 2, 3] }
    

    API 调用 2 接受一个 ID(api(1)、api(2)、api(3) 等)并返回:

    { something: 'else', id: 1 }
    

    在 RxJS 中,您可能希望 switchMap 为您获得的每个 ID,以便您可以将订阅切换到新的 Observable。如果您希望所有这些都在它们进来时进来,您会merge这些。如果你想让他们按顺序进来,你会concat他们。

    基本示例:

    this.http.get<{id: number[]}>('api1').pipe(
       switchMap(ids => {
          return concat(ids.forEach(id => {
               return this.http.get<{ something: string, id: number}>('api2/' + id)
          })
       }).subscribe(console.log)
    

    【讨论】:

      猜你喜欢
      • 2018-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      • 2011-01-08
      • 2016-11-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多