angular - 具有多个插入的 rxjs 运算符
问题描述
我将如何在 Angular 6 中使用 rxjs 插入项目,然后在插入后我需要将不同类型的文件上传到不同的端点,并将新的项目 ID 作为子键,而不必嵌套所有这些调用。
createItemWithAttachments(data:any)
{
this.itemService.insert(data.item).subscribe((newItem:Item)=>{
//attachment type 1s
if(data.attachmentType1.length > 0){
this.attachmentService.upload(data.attachmentType1,
"type1", newItem.id).subscribe(newAttachment=>{
});
}
//attachment type 2s
if(data.attachmentType2.length > 0){
this.attachmentService.upload(data.attachmentType2,
"type2", newItem.id).subscribe(newAttachment=>{
});
}
});
}
解决方案
最好的方法是mergeMap
与 a 一起使用merge
并last
从合并中获取最后一个发出的值。您必须确定在of()
. 如果您从调用中返回一个对象,这应该是undefined
//如果您从上传中返回一个数组,则应该是一个空数组:void 0
null
upload
[]
createItemWithAttachments({ item, attachmentType1: type1, attachmentType2: type2 }): void {
this.itemService.insert(item).pipe(
mergeMap(({ id }: Item) => {
const mergeUpload = [
...(type1.length ? [this.attachmentService.upload(type1, "type1", id)] : []),
...(type2.length ? [this.attachmentService.upload(type2, "type2", id)] : [])
];
return mergeUpload.length ? merge(...mergeUpload) : of([]);
}),
last()
).subscribe((newAttachments) => {
});
}
推荐阅读
- c# - 为什么是 ImmutableList
一个类但 ImmutableArray 一个结构? - mediawiki - 带有链接和内联 html 标签的 MediaWiki 模板
- python - 使用 Python 将 JSON 内容写入 HDFS 位置
- shell - 无法创建先进先出“[Errno 17] 文件存在”
- variables - 将变量的多个值设置为“选项”
- python - 如何使用自定义值在 2D 画布上栅格化 2D 点?
- python - 神经网络的两步训练
- python - 如何使客户端和服务器在 docker 的用户定义网络中相互通信?
- sql - 当信息存储在辅助表中时,如何在 SQL 中查询页面的最新版本?
- javascript - 如何在 React 中仅将 css 应用于此组件?