Make a second http call and use the result in same Observable

后端 未结 2 1464
孤独总比滥情好
孤独总比滥情好 2020-12-18 05:52

I am using angular 2 and it\'s http component.

I want to call a REST API that will return a list of Elements. The size of that list is limited to 100 entries. If the

相关标签:
2条回答
  • 2020-12-18 06:35

    You could leverage the flatMap operator for this:

    call({page: 1})
      .map(res => res.json())
     .flatMap((res) => {
       if(res.meta.hasMore){
         return Observable.forkJoin([
           Observable.of(res),
           call({page: 2}).map(res => res.json()
         ]);
       } else {
         return Observable.of(res);
       }
     })
     .map(data => {
       // if data is an array, it contains both responses of request
       // data[0] -> data for first page
       // data[1] -> data for second page
    
       // if data is an object, it contains the result of the first page
     })
     .subscribe(callback);
    

    The last map operator is to format the data in both cases for the callback specified in the subscribe method.

    0 讨论(0)
  • 2020-12-18 06:40

    Recursion is exactly what the expand operator is for:

    let callAndMap = (pageNo) => call({page: pageNo}).map(res => {page: pageNo, data: res.json()});  // map, and save the page number for recursion later.
    
    callAndMap(1)
    .expand(obj => (obj.data.meta.hasMore ? callAndMap(obj.page + 1) : Observable.empty()))
    //.map(obj => obj.data)    // uncomment this line if you need to map back to original response json
    .subscribe(callback);
    
    0 讨论(0)
提交回复
热议问题