代码之家  ›  专栏  ›  技术社区  ›  Alexis Facques

哪一个算子可以有条件地连接观察值?

  •  4
  • Alexis Facques  · 技术社区  · 9 年前

    分页 ,从REST API,进入我的Angular应用程序。通常,API会按照以下结构向我发送数据:

    {
        "next": null,
        "results": [
            {"id": 7, "name": "Alicia"},
            {"id": 8, "name": "Ted"},
            {"id": 9, "name": "Marshall"}
        ]
    }
    

    哪里 next GET/ 下一个数据页请求。显然,我事先不知道需要迭代多少页才能完全加载数据。

    工作代码 为了充分获取数据( Working plunker here ) :

    public loadPeople( next?:string ): void {
        if(!next) next = 'api/1.json';
    
        this.http.get(next)
            .pipe(
              map( (response: Response) => response.json())
            )
            .subscribe( (data: any) => {
              this._people = this._people.concat(data.results);
              this._peopleSubject.next(this._people);
              if(data.next) this.loadPeople(data.next);
            })
    }
    

    Observables 使用操作员,但我不能把手放在上面。

    你知道我需要一个接线员吗?谢谢

    2 回复  |  直到 6 年前
        1
  •  3
  •   Marco Terzolo Joel    6 年前

    您可以使用 concatMap concat 操作员:

    public loadPage( next:string ): Observable<string[]> {
        return this.http.get(next)
            .pipe(
              map( (response: Response) => response.json() )
              concatMap((data: any) => {
                if (data.next) {
                  return Observable.of(data.results).concat(this.loadPage(data.next));
                }
                return Observable.of(data.results);
              })
            );
    }
    
    public loadPeople( next?:string ): void {
        if(!next) next = 'api/1.json';
    
        this.loadPage(next)
            .subscribe( (people: string[]) => {
                this._people = this._people.concat(people);
                this._peopleSubject.next(this._people);
            })
    }
    

    您将需要以下导入:

    import { of } from 'rxjs'
    import { concat, concatMap,  map } from 'rxjs/operators';
    
        2
  •  0
  •   Vikhyath Maiya    9 年前

    合并地图 同样的。 映射和订阅将用作

    this.http.get('/api/people/1')
      .map(res => res.json())
      .subscribe(character => {
        this.http.get(character.homeworld).subscribe(homeworld => {
          character.homeworld = homeworld;
          this.loadedCharacter = character;
        });
      });
    

    但这样我们可以注意到两件事

    • 首先,我们开始在嵌套中看到这种嵌套金字塔结构 我们的观察值不是很可读。

    • 其次,我们的两个请求是连续的

    因此,我们可以使用mergemap映射/迭代可观察值,如

    this.homeworld = this.http.get('/api/people/1')
      .map(res => res.json())
      .mergeMap(character => this.http.get(character.homeworld))
    

    感谢**科里·瑞兰**,他完美地解释了这一点 enter link description here