如何做rxjs

如何做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(); 
}); 
} 
+0

[链接RxJs观测量的角2](可能的重复http://*.com/questions/37180607/chaining-rxjs-observables-in -angular-2) – rinukkusu

+0

注意你的类型! '.subscribe'返回'Disposable'而不是'Observable' – user3743222

我们可以使用toPromise方法,让您可观察序列转换为一个承诺。

+0

我不想使用它,因为我使用Observables –

+0

还有Rx.Observable.fromPromise方法,它调用promise的then方法来处理成功与错误案例。 – AngJobs

+3

OP请求的关于链式观察的信息 - 链接承诺是无关紧要的 – Corbfon

观察对象的等效thenflatMap。你可以看到这里使用的一些例子:

对于你的榜样,你可以这样做:

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

注重你的函数返回的类型,链式观察值与flatMap你将需要返回一个承诺或可观察。

+5

我不知道我会说flatMap就等于那个。 flatMap实际上对数据执行操作。 http://reactivex.io/documentation/operators/flatmap。html –

+2

如果我们不想要第n个可观察的结果,而是想要没有变换的原始事件,该怎么办? –

如果dosthelsedosanotherthing返回原始值,则要使用的运算符是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(); 
    }); 
}