Angular中如何拆分请求单独发送,是否应当使用flatMap
你完全可以用flatMap实现该需求,RxJS里的flatMap本质是mergeMap的别名,不过你可以根据两个上传请求的依赖关系选择更适配的实现方案:
场景1:两个上传请求无依赖、可并行执行(推荐,性能更高)
如果头像和封面的上传不需要等待彼此返回结果,优先用forkJoin组合两个并行请求,再切换到创建用户的接口即可:
// 分别定义两个独立的上传请求 const uploadProfilePic$ = this.upload(profilePicForm).pipe(take(1)); const uploadCoverPic$ = this.upload(coverPicForm).pipe(take(1)); return forkJoin([uploadProfilePic$, uploadCoverPic$]).pipe( switchMap(([profileRes, coverRes]) => { body.user.profilePic = profileRes.data.profilePic; body.user.coverPic = coverRes.data.coverPic; return this.http.post<IRresponse<object>>(environment.api + EndPoint.CreateUser, body); }) );
场景2:两个上传请求需要串行执行
如果业务要求必须等第一个上传完成才能发起第二个上传,这时候用flatMap就非常合适:
return this.upload(profilePicForm).pipe( take(1), // 第一个上传完成后,通过flatMap发起第二个上传 flatMap(profileRes => { body.user.profilePic = profileRes.data.profilePic; return this.upload(coverPicForm).pipe(take(1)); }), // 第二个上传完成后,发起创建用户请求 switchMap(coverRes => { body.user.coverPic = coverRes.data.coverPic; return this.http.post<IRresponse<object>>(environment.api + EndPoint.CreateUser, body); }) );
补充说明:如果你的上传操作不会频繁连续触发,用flatMap或者switchMap都能满足需求,两者的核心区别是switchMap会在新的事件触发时取消前一个未完成的请求,普通上传场景下两者表现没有差异。
内容的提问来源于stack exchange,提问作者lucas
相关产品推荐
相关产品推荐

