如何在rxjs中做链序 [英] How to do the chain sequence in rxjs

查看:35
本文介绍了如何在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();
});
}

推荐答案

对于 observables 来说,then 的等价物是 flatMap.您可以在此处查看一些使用示例:

The equivalent of then for observables would be flatMap. You can see some examples of use here :

对于您的示例,您可以执行以下操作:

For your example, you could do something like :

this._myService.doSomething()
  .flatMap(function(x){return functionReturningObservableOrPromise(x)})
  .flatMap(...ad infinitum)
  .subscribe(...final processing)

注意你的函数返回的类型,对于使用 flatMap 链接 observables,你需要返回一个 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中做链序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆