首页 > 解决方案 > 具有多个插入的 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=>{    

         });    
    }    
    });    
}

标签: angularrxjs6

解决方案


最好的方法是mergeMap与 a 一起使用mergelast从合并中获取最后一个发出的值。您必须确定在of(). 如果您从调用中返回一个对象,这应该是undefined//如果您从上传中返回一个数组,则应该是一个空数组:void 0nullupload[]

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) => {

  });
}

推荐阅读