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

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

问题描述

我使用的是 angular 2,它是 http 组件.

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

我想调用一个将返回元素列表的 REST API.该列表的大小限制为 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天全站免登陆