【问题标题】:Angular Observable wait for method to execute before returnAngular Observable 等待方法在返回前执行
【发布时间】:2020-12-07 11:08:47
【问题描述】:

在从第一个 observable (this.postService.addPost) 返回值之前,有什么方法可以等待方法完成执行?执行 addPost 添加新帖子后,我希望运行一个基于添加的帖子 ID 上传帖子图片的方法,并等待此方法完成后再返回结果。但是用我写的代码,先返回observable结果,只执行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)
                })
            )

【问题讨论】:

标签: angular rxjs observable


【解决方案1】:

像这样使用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);
  })
)

【讨论】:

    猜你喜欢
    • 2021-06-20
    • 2020-10-25
    • 2018-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多