簡體   English   中英

Angular Observable 等待方法在返回前執行

[英]Angular Observable wait for method to execute before return

在從第一個可觀察對象(this.postService.addPost)返回值之前,有什么方法可以等待方法完成執行? 在執行 addPost 添加新帖子后,我希望運行一個基於添加的帖子 ID 上傳帖子圖片的方法,並等待該方法完成后再返回結果。 但是使用我編寫的代碼,首先返回可觀察的結果,並且只執行了uploadPostImages方法。

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

像這樣使用switchMap

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM