加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 07:34:33 所属栏目:安全 来源:网络整理
导读:我已经阅读了 Rx.js repeat文档,试图找出如何根据我从API收到的响应继续调用api.我正在调用一次只能发回2k条记录的API. API会发回一个值给我发送它,以便我可以继续接收记录,直到它们返回完成值. 所以流程如下: 将GET请求设为查询参数reqMode =”: 使用包含
我已经阅读了 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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读