[英]Angular 2 http - combine multiple Observables
I'm totaly new in async Observable world. 我是异步可观察世界中的新手。 I hope somebody help me. 我希望有人帮助我。
I have two Observable<boolean>
and I want to combine them. 我有两个Observable<boolean>
,我想将它们结合起来。
I tried to use: 我尝试使用:
var obs1 = Observable.of(true).delay(1000);
var obs2 = Observable.of(false).delay(100);
obs1.combineLatest(obs2, (obs1Val, obs2Val) => {
//bool result
});
and thats almost it... almost because I want to start obs2 when obs1 is finished, with combineLatest both starts in the same time. 多数民众赞成在这里...几乎是因为我想在obs1完成后启动obs2,并且CombineLatest都在同一时间启动。
obs1 and obs2 here are simple examples in my case thats angular http requests: 在我的情况下,obs1和obs2是简单的示例,即有角度的http请求:
obs1 : Observable<boolean> = http.get(...).map(d => <boolean>d);
Thanks in advance for help 预先感谢您的帮助
If you want to start obs2 when you get response from obs1, it has to be called in onNext of obs1.subscribe. 如果要在收到obs1的响应时启动obs2,则必须在obs1.subscribe的onNext中调用它。
getBothResult() {
return Rx.Observable.create(function (observer) {
obs1 : Observable<boolean> = http.get(...).map(d => <boolean>d);
obs1.subscribe((obs1Value) {
Observable.of(false).delay(100).subscribe(obs2Value => {
//compute value from obs1Value and obs2Value as they are visible in closure assign it to eg. finalValue
var finalValue = obs1Value + obs2Value;
observer.onNext(finalValue);
});
});
});
}
It's very possible that an operator exists that does all those things in some nifty way, however I'm not aware of it. 存在一个很有可能以某种巧妙的方式完成所有这些操作的操作员,但是我并不知道。
You can use observable zip 您可以使用可观察的拉链
let obs1 = Observable.of(true).delay(1000);
let obs2 = Observable.of(false).delay(100);
let source = Observable.zip(
obs1,
obs2,
(ob1, ob2) => {
return {
value1: ob1,
value2: ob2
};
}
);
source.subscribe(data => console.log(data))
As you want to have obs2 execute after obs1, we can wait for a response In the Rx world, you should avoid subscribing to an observable, and then subscribing to another observable in the callback. 因为您希望obs1之后执行obs2,所以我们可以等待响应。在Rx世界中,您应该避免订阅一个可观察对象,然后在回调中订阅另一个可观察对象。
Here is an approach that should get you the result you are looking for. 这是一种应该为您提供所需结果的方法。
var obs1 = Observable.of(true).delay(1000);
var obs2 = Observable.of(false).delay(100);
var obsOf1And2 = obs1.flatMap(obs1Response =>
obs1Response.flatMap(obs2Response => {
// do what you want with both responses
}));
obsOf1And2.subscribe(console.log);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.