本文介绍了如何在rxjs中执行链序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想要这样的事情:
this._myService.doSomething().subscribe(result => {
doSomething()
});
.then( () => dosthelse() )
.then( () => dosanotherthing() )
所以我想像承诺一样链接.then。我如何在Rxjs中做到这一点?
So I would like to chain .then like in promise. How would I do that in 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();
});
}
推荐答案
对于observable,相当于然后
将是 flatMap
。您可以在这里看到一些使用示例:
The equivalent of then
for observables would be flatMap
. You can see some examples of use here :
- RxJS Promise Composition (passing data)
- Why we need to use flatMap?
- RxJS sequence equvalent to promise.then()?
对于您的示例,您可以执行以下操作:
For your example, you could do something like :
this._myService.doSomething()
.flatMap(function(x){return functionReturningObservableOrPromise(x)})
.flatMap(...ad infinitum)
.subscribe(...final processing)
注意函数返回的类型,以及使用 flatMap
的链可观察量你将需要返回一个promise或一个observable。
Pay attention to the types of what your functions return, as to chain observables with flatMap
you will need to return a promise or an observable.
这篇关于如何在rxjs中执行链序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!