具有多个插入的 rxjs 运算符

rxjs operators with multiple inserts

我将如何在 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=>{    

         });    
    }    
    });    
}

我认为有多种方法可以解决这个问题,但其中一种可能是这样的:

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
    });

最好的方法是将 mergeMapmergelast 一起使用,以从合并中获取最后发出的值。您必须确定要在 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) => {

  });
}