如何做rxjs
链序列我想喜欢的东西:如何做rxjs
this._myService.doSomething().subscribe(result => {
doSomething()
});
.then(() => dosthelse())
.then(() => dosanotherthing())
所以我想链。那么像承诺。我如何在Rxjs中做到这一点?
this._myService.getLoginScreen().subscribe(result => {
window.location.href = MyService.LOGIN_URL;
/// I would like to wait for the site to load and alert something from the url, when I do it here it alerts the old one
});
.then (alert(anotherService.partOfTheUrl())
getLoginScreen() {
return this.http.get(myService.LOGIN_URL)
.flatMap(result => this.changeBrowserUrl())
.subscribe(result => //i want to do sth when the page is loaded//);
}
changeBrowserUrl(): Observable<any> {
return Observable.create(observer => {
window.location.href = myService.LOGIN_URL;
observer.next();
});
}
观察对象的等效then
为flatMap
。你可以看到这里使用的一些例子:
- RxJS Promise Composition (passing data)
- Why we need to use flatMap?
- RxJS sequence equvalent to promise.then()?
对于你的榜样,你可以这样做:
this._myService.doSomething()
.flatMap(function(x){return functionReturningObservableOrPromise(x)})
.flatMap(...ad infinitum)
.subscribe(...final processing)
注重你的函数返回的类型,链式观察值与flatMap
你将需要返回一个承诺或可观察。
我不知道我会说flatMap就等于那个。 flatMap实际上对数据执行操作。 http://reactivex.io/documentation/operators/flatmap。html –
如果我们不想要第n个可观察的结果,而是想要没有变换的原始事件,该怎么办? –
如果dosthelse
或dosanotherthing
返回原始值,则要使用的运算符是map
。如果它是可观察的,那么运营商是flatMap
(或等同的)。
如果你想做一些必要的事情。我的意思是在异步处理链之外,你可以利用do
运算符。
假设dosthelse
返回一个可观察和dosanotherthing
原始对象,你的代码将是:
this._myService.doSomething()
.do(result => {
doSomething();
})
.flatMap(() => dosthelse())
.map(() => dosanotherthing());
请注意,如果您返回SUBCRIBE方法的返回,这将对应一个申购对象,而不是一个观察到的。订阅对象主要是为了能够取消observable而不能参与异步处理链。
事实上,大多数时候,你在订阅链条的末尾订阅。
因此,我将重构你的代码是这样的:
this._myService.getLoginScreen().subscribe(result => {
window.location.href = MyService.LOGIN_URL;
/// I would like to wait for the site to load and alert something from the url, when I do it here it alerts the old one
alert(anotherService.partOfTheUrl()
});
getLoginScreen() {
return this.http.get(myService.LOGIN_URL)
.flatMap(result => this.changeBrowserUrl())
.do(result => //i want to do sth when the page is loaded//);
}
changeBrowserUrl(): Observable<any> {
return Observable.create(observer => {
window.location.href = myService.LOGIN_URL;
observer.next();
});
}
[链接RxJs观测量的角2](可能的重复http://*.com/questions/37180607/chaining-rxjs-observables-in -angular-2) – rinukkusu
注意你的类型! '.subscribe'返回'Disposable'而不是'Observable' – user3743222