使用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
相关产品推荐
相关产品推荐

