angular – Observable继续调用API并根据条件更改参数

我已经阅读了 Rx.js repeat文档,试图找出如何根据我从API收到的响应继续调用api.我正在调用一次只能发回2k条记录的API. API会发回一个值给我发送它,以便我可以继续接收记录,直到它们返回完成值.

所以流程如下:

>将GET请求设为查询参数reqMode =”:
>使用包含值或完成的reqMode的最后一个数组检索响应.
>如果我收到一个值,那么我需要发出相同的请求,但发送带有值的reqMode参数.
>如果我收到了,那么我将停止并返回自第一次通话以来的所有记录.

我在正常订阅时得到第一组值,但这是我在阅读文档后的尝试,但它没有意义:

getRecords(){
    let url = this.url + 'reqMode=';
    return this.http.get(url)
            .doWhile() //What would I do here
}

当尝试使用类型为Observable< response>的Observable执行.doWhile时.我正在寻找使用Observables的任何替代方案,以满足我的需求.

我认为repeat()不是一个好的运算符.如果我理解正确,您希望根据先前请求的响应重复HTTP请求.如果您想多次重复相同的请求,则运算符repeat()很好.

我使用concatMap()并递归调用自己,直到reqMode eqaul为“done”:

观看现场演示:http://plnkr.co/edit/w0DdepslTaKrLSB3aIkA

import {Observable,Subject} from 'rxjs';

const result = new Subject();
const closeBuffer = new Subject();
const buffer = result.buffer(closeBuffer.asObservable());

function sendHttpRequest(reqMode) {
  return Observable.of('{"reqMode":' + reqMode + '}')
    .map(response => JSON.parse(response))
    .concatMap(data => {
      console.log('HTTP Response:',data);
      // Add data to the buffer of results
      result.next(data);

      if (data.reqMode == 'done') {
        // Return an empty value wrapped as an Observable so concatMap can work
        // with it and emit onNext when it completes (which is immediately
        // thanks to the `.of()` operator).
        return Observable.of(null);
      } else {
        // Simulate that the next call returns 'done'
        return sendHttpRequest('"done"');

        // Uncomment this for real usage
        //return sendHttpRequest(data.reqMode);
      }
    });
}

// Subscribe to the buffer where I'll receive the value.
buffer.subscribe(val => console.log('Next: ',val));

// Simulate HTTP request with reqMode = 42
sendHttpRequest(42).subscribe(() => {
  console.log('done');
  // Emit values from the buffer.
  closeBuffer.next(null);
  closeBuffer.complete();
});

我使用of()运算符来模拟请求并返回包含为Observable的值.我还使用Subject来保存使用buffer()运算符缓冲的所有响应.我订阅缓冲区以获取最终的响应数组(如果将此代码包装到函数中,您很可能会返回缓冲区,您可以在以后订阅).

回应如下:

HTTP Response: Object {reqMode: 42}
HTTP Response: Object {reqMode: "done"}
Next:  [Object,Object]

看到类似的问题:Angular 2 + rxjs – how return stream of objects fetched with several subsequent http requests

相关文章

ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...