2017-01-04 53 views
0

在我的片段,我做一个API请求,一切工作正常。我现在正在检查响应,以查看服务器上可用项目的总数是否大于页面大小所定义的返回结果集。如果是这样,我想进行额外的api调用,直到检索到所有结果并作为一个响应返回给订阅者。我需要使用哪个RX操作员来完成此操作,以及如何暂停下面的响应返回,直到后续的api调用完成?RX合并多个观测

getAction<T>(path: string, params?: {}): Observable<T> { 
 
     return this._http.get("url") 
 
      .map(res => { 
 
       let response = res.json(); 
 
       // If more pages available make additional api calls & return as single result 
 
       return response; 
 
      }); 
 
    }

+1

因为这是一个线性流,在1个发射完成后''switchMap','flatMap'或'concatMap'应该在你的情况下工作相同 - 当怀疑链接多个流时使用'switchMap',在大多数情况下 – olsn

回答

1

看看​​。

要递归获取数据的多个页面,你可以这样做:

class MyExample { 
    search(offset) { 
    return this.http.get(`/search?offset=${offset}`); 
    } 

    searchAll() { 
    return this.search(0) 
       .expand(results => { 
       if (loadNextPage(results)) { 
        return this.search(results.nextPageOffset); 
       } else { 
        return Observable.empty(); 
       } 
       }); 
    } 
} 

expand允许您根据之前的结果(如检查是否有更多页)做一些处理,并指定Observable有更多的结果。所有这些调用的结果将被连接起来,不需要担心将它们放在自己身上。

1

你应该使用switchmap,直到你把所有的数据,以获得从其他观察到的响应。只是将所有响应连接起来,并将其作为最后可观察到的响应返回。例如:

//emit immediately, then every 5s 
const source = Rx.Observable.timer(0, 5000); 

//switch to new inner observable when source emits, emit items that are emitted 
const example = source.switchMap(() => Rx.Observable.interval(500)); 

//output: 0,1,2,3,4,5,6,7,8,9...0,1,2,3,4,5,6,7,8 
const subscribe = example.subscribe(val => console.log(val));