-1

I have a method that returns an Observable. I need to return the observable, but only after the subsribe:

    public dataSelector(params: any): Observable<any> {
        job$.subscribe((job) => {
            this.folderService
              .getFolder(job.parentFolderID)
              .subscribe((folder) => {
                console.log('hello');
              });
          });
          return job$;
}

In this case, I'm returning obseravle job$, but I want to return it only after it is done with the subscribe, meaning only afte rthe console.log('hello') is triggered.

Currently, the job$ observable is returned first, and only after that the subscribe is being triggered

Roni Axelrad
  • 399
  • 3
  • 13
  • Yes, you cannot return an observable as you have shown. Having nested subscribes is also not recommended. What are you trying to do exactly? Maybe we can help propose an alternative. – DeborahK Jan 24 '19 at 22:01

1 Answers1

2

You need to use some more RXJS operators to properly transform the observable into something that returns the format you want without the use of any subscribes. The switchMap operator lets you return an observable which is the result of an inner observable which should get you up and running:

import { switchMap } from 'rxjs/operators';

 public dataSelector(params: any): Observable<any> {
   return job$.pipe(
     switchMap(job => this.folderService.getFolder(job.parentFolderID)
   );
 }

Someone calling this function will be able to subscribe to the result and will receive the resolved folder once the inner observable completes:

dataSelector({}).subscribe(x => */ x is folder here */);

Jesse Carter
  • 20,062
  • 7
  • 64
  • 101