-1

I need to get data from redux store to make another api call and the response needs to be saved to the store. How can we avoid callback hell in this case.

Following is the code snippet which subscribes to the observable.

Store

this.user$ = this.store.select('user');
this.dataStore$ = this.store.select('dataStore')

Callback Hell

this.user$.subscribe((user: any) => {
  this.abcService.getData(user.id).subscribe((data:any) => {
    this.data = data;
    this.dataStore$.dispatch(abcAction(data));
  }
}

How to avoid this above callbacks. In promise world we could easily chain promises. Since observables are not chainable, how do we avoid nested callbacks and what is the best way to write above code. Would like to know how best rxjs operators can be applied.

Any help is greatly appreciated.

Vishnu Sureshkumar
  • 2,246
  • 6
  • 35
  • 52
  • 2
    Possible duplicate of [Angular 2: Two backend service calls on success of first service](http://stackoverflow.com/questions/36712659/angular-2-two-backend-service-calls-on-success-of-first-service) – eko May 19 '17 at 13:40

1 Answers1

4

You want to leverage many operators rxjs provides. For example, you can re-write the above code as following:

this.user$
.flatMap((user: any) => this.abcService.getData(user.id))
.subscribe((data: any) => {
    this.data = data;
    this.dataStore$.dispatch(abcAction(data));    
});

You can think of these different operators as your Promise then()s but more powerful because they can do more.

lbrahim
  • 3,710
  • 12
  • 57
  • 95