处方药。为什么 subject 在 mergeMap 之后只发射一次?

RxJs. Why a subject emits only once after mergeMap?

我有几个链接,其中一个代表用户的活动订单。当用户点击它时,我想向 API 发送一个 HTTP DELETE 请求。我的组件 ts 文件中有一个函数,它是从我的模板中调用的,如下所示:

// Component
interface CancelCommand {
    orderId: string
}
private cancelCommands = new Subject<CancelCommand>();

/* Get called from a template on click, like so 
          <a ... (nzOnConfirm)="cancel(ord.id)">Cancel</a> */
cancel(orderId: string) {
    this.cancelCommands.next({
        orderId: orderId
    })
}

我在 ngOnInit 中订阅主题 cancelCommands:

// Component
ngOnInit(): void {
    this.cancelSub = this.cancelCommands.pipe(
        mergeMap((command) => this.service.cancelOrder(command)))
    ).subscribe()
}

在服务中 cancelOrder 函数只是调用 HttpClient

// The Service
cancelOrder(command: CancelCommand) : Observable<CommandResponse> {
      return this.http.delete<CommandResponse>(`${this.url}/${command.orderId}`)
}

我的问题是,为什么带有 this.cancelSub 订阅的可观察对象在第一个订单取消后停止发出值?

谢谢大家的提示!在你的帮助下,我想通了。当我的一个请求 return 出现错误并且 observable 停止时,发生了错误。我已经这样修复了,看起来没问题。

    this.cancelSub = this.cancelCommands.pipe(
      mergeMap((command) => this.service.cancelOrder(command)),
      catchError((_, caught) => caught) // new line
    ).subscribe()

@PilgrimViis 你检查过可观察对象 this.cancelSub 是否真的完成了吗?

@TmTron 我检查了当源 observable 完成时 mergeMap 是否完成,这里不是这种情况:https://stackblitz.com/edit/rxjs-qthnmy?devtoolsheight=33&file=index.ts