使用 switchmap 和 forkjoin 链接可观察量无法按预期的角度打字稿 rxjs 工作

kei*_*eil 5 javascript observable rxjs angularjs typescript

我目前正在尝试创建一个系统,如果我成功更新了请求,我会在 forkjoin 中触发 3 个可观察量,然后一旦这些完成,console.log('complete/or finish') 否则,如果没有,则不执行任何操作。目前,虽然可观察量在分叉连接完成之前就已完成,但我完全不知道发生了什么,

  copyAttachments(): Observable<any> {
    if (this.model.attachments.length > 0) {
      return this.attachmentService.copyAttachments(this.model.attachments, this.model.id);
    }
    return empty();
  }

  uploadAttachments(): Observable<any> {
    this.showAttachmentsUploadingModal = true;
    const formData = new FormData();

    if (this.formAttachments.length > 0) {
      this.showAttachmentsUploadingModal = true;
      this.formAttachments.forEach(file => {
        formData.append('files', file, file.name);
      });
    }

    // uploading empty formData will still trigger creation of default folder structure
    return this.attachmentService.uploadAttachments(formData, this.model.id);
  }

  uploadCustomerData(): Observable<any> {
    this.showAttachmentsUploadingModal = true;
    const formData = new FormData();

    if (this.formCustomerData.length > 0) {
      this.showAttachmentsUploadingModal = true;
      this.formCustomerData.forEach(file => {
        formData.append('files', file, file.name);
      });
      return this.attachmentService.uploadCustomerData(formData, this.model.id);
    }

    return empty();
  }
Run Code Online (Sandbox Code Playgroud)

handleAttachments(): Observable<any> {
    return forkJoin
      (
        this.copyAttachments(),
        this.uploadCustomerData(),
        this.uploadAttachments()
      )
  }

  updateRequest() {
    this.myservice
      .updateRequest(this.model)
      .pipe(
        switchMap((saveResult: boolean) => {
          this.showSubmittingModal = false;
          if (saveResult === true) {
            return this.handleAttachments();
          } else {
            return empty();
          }
        }),
      )
      .pipe(finalize(() => {
        console.log('finish')
      }))
      .subscribe(
        response => {
          // todo: do anything with this response from uploadAttachments()?
          this.showAttachmentsUploadingModal = false;
        },
        error => {
          location.reload();
        },
        () => {
          console.log('complete')
        }
      );
  }
Run Code Online (Sandbox Code Playgroud)

预期结果是我的服务完成,然后我的 forkjoin 可观察对象完成,然后它将 console.log('finish')

目前结果是服务完成。它 console.logs('finish') 然后我的 forkjoin 触发

kei*_*eil 0

我发现这个问题的解决方案是返回一个空对象作为可观察对象,而不是返回empty()或of(),这样Forkjoin仍然保持值,所以返回of({})并且一切都很好