angular – Observable继续调用API并根据条件更改参数
我已经阅读了
Rx.js repeat文档,试图找出如何根据我从API收到的响应继续调用api.我正在调用一次只能发回2k条记录的API. API会发回一个值给我发送它,以便我可以继续接收记录,直到它们返回完成值.
所以流程如下: >将GET请求设为查询参数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()很好.
我使用 观看现场演示: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(); }); 我使用 回应如下: 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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |