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

Observable Continue calling API and changing parameters based on condition

我阅读了 Rx.js repeat 文档,试图了解如何根据从 API 收到的响应继续调用 api。我正在调用一次只能发回 2k 条记录的 API。 API 将发回一个值供我发送,以便我可以继续接收记录,直到他们 return 完成值。

所以流程如下:

  1. 发出一个GET请求一个查询参数reqMode='':
  2. 检索包含 reqModevaluedone 的最后一个数组的响应。
  3. 如果我收到 value,那么我需要发出相同的请求,但发送带有值的 reqMode 参数。
  4. 如果我收到 done 那么我将停止并 return 自第一次通话以来的所有记录。

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

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

当尝试对 Observable<response> 类型的 Observable 执行 .doWhile 时。我正在寻找使用 Observables 的任何替代方法来完成我需要做的事情。

所以我举了一个例子,说明如何使用包装 observer.repeat()

所有逻辑都在app.component.ts

Checkout this plunker

我在代码中留下了评论,但本质上它会发出一个 http 请求,它会增加一个计数,然后用不同的查询编号发出另一个请求。它将重复直到达到 5。

您必须对其进行修改,使 "repeat condition" 代表您的逻辑。

希望对您有所帮助!

我认为 repeat() 不是一个好的运算符。如果我对你的理解是正确的,你想根据前一个请求的响应重复 HTTP 请求。如果您想多次重复 相同的 请求,运算符 repeat() 非常有用。

我会使用 concatMap() 并递归调用自身,直到 reqMode 等于 "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() operator to simulate a request and to return a value wrapped as an Observable. I also use Subject to hold all responses that are buffered using buffer() 运算符。我订阅缓冲区以获得最终的响应数组(如果您将此代码包装到一个函数中,您很可能 return buffer 稍后您可以在其中订阅)。

回复如下:

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

查看类似问题: