1

Is there any way to wait for a method to finish executing before returning a value from the first observable (this.postService.addPost) ? After executing addPost to add new post, i wish to run a method to upload post image based on the added post Id and wait for this method to complete before returning a result. But with the code i written, the observable result is returned first and only executed the uploadPostImages method.

             this.postService.addPost(post).pipe(
                map((newPost: Post) => {
                    
                    if(selectedFilePaths.length !== 0) {      
                        this.imageService.uploadPostImages(newPost, selectedFilePaths);  <--wait for this to finish before return newPost
                    }

                    
                    return newPost; <-- this should execute after uploadPostImages (If selectedFilePaths not 0)
                })
            )
scholarwithfire
  • 345
  • 2
  • 8
  • 21
  • `switchMap`, instead of `map` – Ashish Ranjan Dec 07 '20 at 11:10
  • Does this answer your question? [How do I return the response from an Observable/http/async call in angular?](https://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular) – R. Richards Dec 07 '20 at 11:10

1 Answers1

2

Use switchMap like this

this.postService.addPost(post).pipe(
  switchMap((newPost: Post) => {
    if(selectedFilePaths.length !== 0) {      
      return this.imageService.uploadPostImages(newPost, selectedFilePaths).pipe(
        map(() => newPost),
      );
    }
    return of(newPost);
  })
)
MoxxiManagarm
  • 8,735
  • 3
  • 14
  • 43