You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ng DrawerService调用异常:调用ViewPurchaseOrder却加载错误组件

问题排查与解决方案

根据你提供的代码和问题场景,核心原因是NgZorro DrawerService 默认会缓存组件实例:关闭ViewCreateOrder对应的抽屉后,ViewProductCartComponent实例未被彻底销毁,后续调用ViewPurchaseOrder时,抽屉复用了之前缓存的错误组件实例,而非创建新的NewPurchaseComponent实例。

以下是具体的解决办法:

一、强制关闭时销毁组件实例

在调用drawerService.create()时添加nzDestroyOnClose: true配置,确保抽屉关闭后立即销毁对应组件实例,避免后续复用错误组件:

ViewPurchaseOrder(item: any): void {
   this.drawerService.create({
      nzTitle: 'View Purchase Order',
      nzMaskClosable: true,
      nzWrapClassName: "full-drawer noSidebar",
      nzContent: NewPurchaseComponent,
      nzContentParams: { purchaseOrderData: item },
      nzDestroyOnClose: true // 新增:关闭抽屉时销毁组件
   });
 }

ViewCreateOrder(item: any): void {
    this.drawerService.create({
      nzTitle: 'View Create Order',
      nzMaskClosable: true,
      nzWrapClassName: "md-drawer",
      nzContent: ViewProductCartComponent,
      nzContentParams: { createOrderData: item },
      nzDestroyOnClose: true // 新增:关闭抽屉时销毁组件
    });
}

二、手动管理抽屉实例并销毁

如果上述配置未生效,可以手动保存抽屉实例引用,在打开新抽屉前主动销毁旧实例:

private currentDrawer: any;

ViewPurchaseOrder(item: any): void {
   // 销毁之前的抽屉实例(如果存在)
   this.currentDrawer?.destroy();
   this.currentDrawer = this.drawerService.create({
      nzTitle: 'View Purchase Order',
      nzMaskClosable: true,
      nzWrapClassName: "full-drawer noSidebar",
      nzContent: NewPurchaseComponent,
      nzContentParams: { purchaseOrderData: item }
   });
 }

ViewCreateOrder(item: any): void {
    // 销毁之前的抽屉实例(如果存在)
    this.currentDrawer?.destroy();
    this.currentDrawer = this.drawerService.create({
      nzTitle: 'View Create Order',
      nzMaskClosable: true,
      nzWrapClassName: "md-drawer",
      nzContent: ViewProductCartComponent,
      nzContentParams: { createOrderData: item }
    });
}

三、检查组件状态污染

确认NewPurchaseComponent和ViewProductCartComponent是否存在全局状态共享(如单例服务、静态变量)的情况,这类状态可能导致组件实例复用后异常。若存在,需在组件的ngOnDestroy钩子中清理状态:

// 示例:在组件内清理状态
ngOnDestroy(): void {
  // 重置组件内部状态变量
  this.purchaseOrderData = null;
  // 取消所有异步数据流订阅(如果有)
  this.dataSubscription?.unsubscribe();
}

内容的提问来源于stack exchange,提问作者Shawn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 12:12:15