我不认为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()
运算符缓冲的所有响应。我订阅缓冲区以获得最终的响应数组(如果将此代码封装到函数中,您很可能会返回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
angular2附带rxjs5-β和基于您将无法使用.doWhile文档中......至少目前还没有:https://github.com/ReactiveX/rxjs/blob/master/MIGRATION.md#operators-renamed-or-removed。你在寻找替代解决方案吗?或只为rxjs4? – mrcolombo
我很好,有替代品。 – inspired