进行第二次http调用并在同一个Observable中使用结果 [英] Make a second http call and use the result in same Observable

查看:90
本文介绍了进行第二次http调用并在同一个Observable中使用结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用angular 2和它的http组件。

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

我想调用一个REST API来返回一个Elements列表。该列表的大小限制为100个条目。如果有更多项目,将在响应中设置 hasMore 标志。然后,您必须使用参数page = 2再次调用API。有一个Observable,两个服务器响应都会很好。
我的代码如下所示:

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 there are more items a hasMore flag will be set in the response. You then have to call the API again with the parameter page=2. It would be nice to have one Observable, with both server responses. My code looks something like this:

call({page: 1})
  .map(res => res.json())
  .do((res) => {
    if(res.meta.hasMore){
      // do another request with page = 2
    }
  }
  .map(...)
  .subscribe(callback)

call 是一个函数,它将使用http模块发出请求并返回一个Observable。在if语句的内部我要制作另一个http请求并将结果放在同一个Observable上,以便在subscribe中注册的回调将被调用两次(每次响应一次)。

call is a function that will use the http module to make the request and return an Observable. Inside of the if statement I want to make another http request and put the result on the same Observable, so that the callback, registered with subscribe, will be called twice (one time for each response).

我是我不太确定怎么做。我尝试使用flatMap来发出下一个请求,但没有成功。

I am not really sure how to do it. I tried using flatMap to make the next request, but had no success.

推荐答案

递归是正是扩展运算符的用途:

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);

这篇关于进行第二次http调用并在同一个Observable中使用结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆