![](/img/trans.png)
[英]How to wait for a observable method to finish before proceeding in Angular 2
[英]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.