简体   繁体   中英

Angular Observable wait for method to execute before return

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)
                })
            )

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);
  })
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM