What is the best way to chain observables in Angular?

Viewed 4812

If I have a service call that relies on the result of another service call what is the best way to chain them?

myService.getStuffFromServer().subscribe(data => {
  let manipulatedData = functionThatManipulatesData(data);
  myService.getMoreStuffFromServer(manipulatedData).subscribe(moreData => {
    doStuffWithMoreData(moreData);
  });
});

Is the way I have been doing it but the nesting gets a bit messy sometimes. Is there a cleaner way?

3 Answers

For rxjs 6.x.x (tested with 6.5.4), we need to add the pipe() function like this:

myService.getStuffFromServer()
  .pipe(
    map(functionThatManipulatesData), 
    flatMap(manipulatedData =>
        myService.getMoreStuffFromServer(manipulatedData)))
  .subscribe(moreData => {
    doStuffWithMoreData(moreData);
   });

To get it to work correctly.

Related