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

使用ngx-notification-bar跳转页面时报unsubscribe未定义错误

问题解决办法

该错误是ngx-notification-bar库本身的代码缺陷导致的:库内置的NotificationBarComponent在ngOnDestroy生命周期中直接调用了订阅对象的unsubscribe方法,没有做非空校验,当组件销毁时如果订阅还未完成初始化,就会抛出空指针异常,阻塞路由跳转流程导致页面空白。可选择以下任意一种方案解决:

  • 方案1:主动销毁通知栏实例

    在创建通知栏时保存实例引用,当前组件销毁前主动销毁通知栏:
    修改app.component.ts代码:

    // 声明变量存储通知栏实例
    private notificationRef: any;
    
    // 创建通知时保存实例
    this.notificationRef = this.notificationBarService.create({ 
      message: '<b>Free Shipping </b>', 
      type: NotificationType.Info, 
      allowClose: true, 
      autoHide: false, 
      hideOnHover: false, 
      isHtml: true 
    });
    
    // 新增ngOnDestroy钩子主动销毁
    ngOnDestroy(): void {
      if (this.notificationRef) {
        this.notificationRef.destroy();
      }
    }
    
  • 方案2:全局放置通知栏组件

    如果通知栏需要全局展示,把notification-bar组件移动到app.component.html的路由出口外部,让它不会随着路由切换销毁,也就不会触发销毁阶段的报错:

    <!-- app.component.html 全局结构示例 -->
    <notification-bar
      [ngStyle]="{ height: '3px', background: 'white' }"
    ></notification-bar>
    <router-outlet></router-outlet>
    
  • 方案3:修复库代码缺陷

    直接修改库的报错逻辑,给unsubscribe调用加非空校验:
    找到node_modules/ngx-notification-bar/bundles/ngx-notification-bar.js文件第165行,将原代码:

    this.subscription.unsubscribe();
    

    替换为:

    if (this.subscription) this.subscription.unsubscribe();
    

    可配合patch-package工具固化该修改,避免后续重装依赖时修改被覆盖。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 19:57:03