I would like to to something like:
this._myService.doSomething().subscribe(result => { doSomething() }); .then( () => dosthelse() ) .then( () => dosanotherthing() )
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(); }); }
RxJS' pipe() is both a standalone function and a method on the Observable interface that can be used to combine multiple RxJS operators to compose asynchronous operations. The pipe() function takes one or more operators and returns an RxJS Observable.
RxJS' of() is a creational operator that allows you to create an RxJS Observable from a sequence of values. According to the official docs: of() converts the arguments to an observable sequence. In Angular, you can use the of() operator to implement many use cases.
To use concatMap in Angular first we need to import it our Component or Service. import { concatMap } from 'rxjs/operators'; In the following code, we have two observables srcObservable which emits 1,2,3,4 & innerObservable which emits 'A','B','C','D' . The ConcatMap receives its values from the srcObservable .
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With