Abd*_*eed 4 rxjs typescript rxjs5 angular
我已经阅读了Rx.js重复文档,试图找出如何根据我收到的响应继续调用api API.我打电话给一个API只能一次发回2k记录的人.API将为我发回一个值以便发送它,以便我可以继续接收记录,直到它们返回完成值.
所以流程如下:
GET请求查询参数reqMode='':reqMode使用带有value或的最后一个数组检索响应done.value然后我需要发出相同的请求,但发送reqMode带有值的参数.done那么我将停止并返回自第一次通话以来的所有记录.我什么时候得到第一组值subscribing normally,但这是我在阅读文档后的尝试,但这没有意义:
getRecords(){
let url = this.url + 'reqMode=';
return this.http.get(url)
.doWhile() //What would I do here
}
Run Code Online (Sandbox Code Playgroud)
尝试.doWhile使用类型的Observable时Observable<response>.我正在寻找使用Observables的任何替代方案,以满足我的需求.
我认为这不是repeat()一个好的运营商.如果我理解正确,您希望根据先前请求的响应重复HTTP请求.repeat()如果您想多次重复相同的请求,则运营商很好.
我会使用concatMap()并递归调用自己直到reqModeeqaul 为止"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();
});
Run Code Online (Sandbox Code Playgroud)
我使用of()运算符来模拟请求并返回一个包含为Observable的值.我还Subject用来保存使用buffer()operator 缓冲的所有响应.我订阅缓冲区以获取最终的响应数组(如果将此代码包装到函数中,您很可能会返回buffer稍后可以订阅的位置).
回应如下:
HTTP Response: Object {reqMode: 42}
HTTP Response: Object {reqMode: "done"}
Next: [Object, Object]
Run Code Online (Sandbox Code Playgroud)
请参阅类似的问题:Angular 2 + rxjs - 如何使用多个后续http请求返回对象的返回流
| 归档时间: |
|
| 查看次数: |
3672 次 |
| 最近记录: |