Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly chain rxjs 6 observables?

Any suggestions, how this can be rewritten in more promise-chaining style?:

this.apiService.sendPutRequest('/api/users/activate', usrObj).pipe(
        map(() => {
            return this.apiService.sendGetRequest('/api/users/' + this.currentUserId).pipe(
                map(data => {
                    return this.setActiveUser(data).pipe(
                        map(() => {
                            return this.apiService.sendGetRequest('api/tasks/user/' + this.currentUserId).pipe(
                                map(tasks => {
                                    return this.taskService.setCurrentUserTasks(tasks);
                                })
                            );
                        })
                    );
                })
            );
        })
    );
like image 541
askona Avatar asked Oct 12 '18 07:10

askona


People also ask

How do I use RxJS observable in Angular 6?

You can create the simple observable in Angular like the following code. import { Observable } from 'rxjs'; // create observable const simpleObservable = new Observable((observer) => { // observable execution observer. next('Hello Observable'); observer. complete(); }); // subscribe to the observable simpleObservable.


2 Answers

You can use switchMap for handling observables and tap for side efects handling. And you need to subscribe because it's cold observable

For error handling use catchError for all requests

this.apiService.sendPutRequest('/api/users/activate', usrObj).pipe(
    catchError(err=> this.errorHandler(err)),
    switchMap(() => this.apiService.sendGetRequest('/api/users/' + this.currentUserId)
        .pipe(catchError(err=> this.errorHandler(err)))
    ),
    tap(data => this.setActiveUser(data)),
    switchMap(() => this.apiService.sendGetRequest('api/tasks/user/' + this.currentUserId)
        .pipe(catchError(err=> this.errorHandler(err)))
    ),
    tap(tasks => this.taskService.setCurrentUserTasks(tasks))
).subscribe()
like image 101
Kliment Ru Avatar answered Oct 02 '22 22:10

Kliment Ru


use SwitchMap for that.

mainApiCall.pipe(
    switchMap(result=>secondApiCall(result)),
    switchMap(resultFromSecondApiCall=>thirdApiCall(resultFromSecond))
...
and so on
)
like image 44
Antoniossss Avatar answered Oct 02 '22 21:10

Antoniossss