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

Angular注入Ngrx Store到ErrorHandler工厂导致循环依赖如何解决

问题原因

Angular的ErrorHandler是框架初始化阶段就会实例化的核心服务,NgRx的Store初始化链路中本身就依赖了ErrorHandler处理状态流中的异常,直接在ErrorHandler的工厂依赖里声明Store会触发双向依赖的循环检测。

解决方案:使用Injector懒加载Store

不要在ErrorHandler的初始化依赖中直接注入Store,改为注入Injector,在错误实际触发、需要用到Store数据的时候再从Injector中获取实例,绕开初始化阶段的依赖检测。
推荐自定义ErrorHandler实现类,逻辑更易维护:

import { ErrorHandler, Injectable, Injector } from '@angular/core';
import { Store } from '@ngrx/store';
import * as Sentry from '@sentry/angular';
import { AppState } from './你的AppState定义路径';

@Injectable()
export class CustomSentryErrorHandler implements ErrorHandler {
  // 构造函数只注入Injector,不直接注入Store
  constructor(private injector: Injector) {}

  handleError(error: unknown): void {
    // 错误触发时再获取Store实例,此时Store已完成初始化
    const store = this.injector.get<Store<AppState>>(Store);
    // 此处可读取Store中需要传入Sentry的参数,比如用户信息、运行上下文等
    // 示例:store.select(currentUser).pipe(take(1)).subscribe(user => Sentry.setUser(user))

    // 调用Sentry默认错误处理逻辑
    const sentryHandler = Sentry.createErrorHandler({
      showDialog: true,
      dialogOptions: {},
    });
    sentryHandler.handleError(error);
  }
}

对应的Provider配置修改为:

{
  provide: ErrorHandler,
  useClass: CustomSentryErrorHandler,
  deps: [Injector],
}

补充说明

如果需要提前把Store的全局数据同步到Sentry上下文,可以放在APP_INITIALIZER的逻辑中执行,不需要耦合到ErrorHandler的初始化流程。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 10:36:07