如何解决RxJS:获得多个响应 更新:使用iif函数代替filter运算符更新:在avatar内检查flatMap
我有“嵌套”请求,团队创建和团队头像上传,其中第二个依赖于第一,并且仅当头像不为null时才应发送(我已经使用过滤器运算符完成了此操作)。我现在需要的是在subscription方法中访问两个响应。
this.team.createTeam(teamRequest)
.pipe(
filter(() => avatar),flatMap(next => this.team.uploadLogo(avatar,next.body.uuid)
).subscribe(responses => {
// so,I want response from both createTeam and uploadLogo in responses
});
解决方法
您可以将map
运算符传递给内部请求并发送两个响应。尝试以下
this.team.createTeam(teamRequest)
.pipe(
filter(() => avatar),flatMap(next =>
this.team.uploadLogo(avatar,next.body.uuid).pipe(
map(res => ({ avatar: res,team: next }))
)
)
).subscribe(responses => {
// responses.avatar: response from `this.team.uploadLogo(avatar,next.body.uuid)`
// responses.team: response from `this.team.createTeam(teamRequest)`
});
我返回了一个对象用于说明。您可以根据需要以任何形式返回它。例如。作为数组map(res => [ next,res ]))
。
更新:使用iif
函数代替filter
运算符
如果在filter
条件失败时仍希望订阅可观察的源,那么我想到的最快方法是放弃filter
运算符,而使用iif
函数。尝试以下
const upload = (avatar,team): Observable<any> => {
return this.team.uploadLogo(avatar,next.body.uuid).pipe(
map(res => ({ avatar: avatar,team: team }))
);
};
iif(() =>
!!avatar,this.team.createTeam(teamRequest).pipe(flatMap(next => upload(avatar,next.body.uuid))),this.team.createTeam(teamRequest)
).subscribe(
responses => {
// if `avatar` is null
// responses: response from `this.team.createTeam(teamRequest)`
// or
// if `avatar` is non-null
// responses.avatar: response from `this.team.uploadLogo(avatar,next.body.uuid)`
// responses.team: response from `this.team.createTeam(teamRequest)`
}
);
更新:在avatar
内检查flatMap
如@ bryan60所建议,这是一个更干净的代码,它既不使用filter
也不使用iif
。而是检查avatar
内的flatMap
并返回of(next)
(如果为空)。
this.team.createTeam(teamRequest).pipe(
flatMap(next => {
if (!!avatar) {
return this.team.uploadLogo(avatar,team: next }))
);
}
return of(next);
})
).subscribe(responses => {
// if `avatar` is null
// responses: response from `this.team.createTeam(teamRequest)`
// or
// if `avatar` is non-null
// responses.avatar: response from `this.team.uploadLogo(avatar,next.body.uuid)`
// responses.team: response from `this.team.createTeam(teamRequest)`
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。