angular - 角。从 switchMap 内的订阅中获取价值
问题描述
我有用户个人资料编辑表格。如果用户上传照片,我需要将其上传到后端,获取图片名称作为响应(例如timestamp_name.jpg)并将此名称与其他提供的属性一起保存,例如姓名、电子邮件等。在存储效果中,我尝试通过以下方式进行操作:
@Effect()
profileUpdated$ = this.actions$.pipe(
ofType<ProfileUpdated>(UserActionTypes.ProfileUpdated),
map(action => action.payload),
switchMap(payload => {
if (!!payload.picture) {
this.uploadResource.image(payload.picture.files[0]).subscribe((res) => payload.picture = res);
}
return this.userResource.updateMyself({user: payload});
}),
);
但是属性图片没有改变,导致它在订阅中。是否有另一种解决方案来实现它?
解决方案
您检测到subscribe
问题是正确的。Asubscribe
永远不应出现在运算符中。只有profileUpdated$
需要订阅的最终消费者。以下是您的代码的修改版本:
profileUpdated$ = this.actions$.pipe(
ofType<ProfileUpdated>(UserActionTypes.ProfileUpdated),
map(action => action.payload),
// Upload image if needed
switchMap(payload => {
if (!!payload.picture) {
return this.uploadResource.image(payload.picture.files[0]).pipe(
map(res => {
payload.picture = res;
return payload;
})
);
} else {
// A switchMap operator must always return an Observable,
// so in the case where no image needs to be uploaded
// we simply return the original payload as an Observable.
return of(payload);
}
}),
// Update profile information
switchMap(payload => this.userResource.updateMyself({user: payload}))
);
推荐阅读
- soundcloud - Soundcloud X-Cache:尝试获取访问令牌时来自云端的错误
- node.js - 在 Jest Node.js 测试中从响应中检索 JSON
- sql-server - SQL 选择所有记录或特定记录
- css - Angular Material Sortable Table - 由于一些我无法解决的全球问题,排序箭头未显示,我错过了什么?
- java - 如何更改日期格式以解析为 url_string?
- django-celery - 从特定时间定期发送电子邮件 django celery
- apache-kafka - FlinkKafkaConsumer 未从远程 Kafka 服务器消费
- python - 根据是否包含特定行数的特定值来选择行范围
- ios - 我可以在 Xcode 9 中添加对 Swift 2 的支持吗
- r - data.table 的打印仅适用于第二次调用。奇怪的行为