【问题标题】:Make a second http call and use the result in same Observable进行第二次 http 调用并在同一个 Observable 中使用结果
【发布时间】:2016-11-13 12:20:24
【问题描述】:

我正在使用 angular 2,它是 http 组件。

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

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 的回调将被调用两次(每个响应一次)。

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

【问题讨论】:

    标签: javascript angular rxjs


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      您可以为此利用flatMap 运算符:

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

      最后一个map 运算符用于在两种情况下为subscribe 方法中指定的回调格式化数据。

      【讨论】:

      • 感谢您的回答。它只适用于两页,但第二次调用可能会再次设置 hasMore 标志。我想我需要这样的递归调用:pastebin.com/JnDu1uJz 另外,我想立即显示已经存在的结果,并在其他结果出现时添加它们。我使用 startWith 并扫描它。对吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-07
      相关资源
      最近更新 更多