我如何在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
和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) => {
});
}
我认为有多种方法可以解决这个问题,但有一种方法可能是这样的:
this.itemService.insert(data.item)
.pipe(
take(1),
mergeMap((newItem:Item) => {
const attachmentUpdateObservables = [];
if(data.attachmentType1.length > 0){
attachmentUpdateObservables.push(this.attachmentService.upload(data.attachmentType1, "type1", newItem.id));
}
if(data.attachmentType2.length > 0){
attachmentUpdateObservables.push(this.attachmentService.upload(data.attachmentType2, "type2", newItem.id));
}
return combineLatest(attachmentUpdateObservables);
})
.subscribe(newAttachments => {
// Do something
});