首页 > 解决方案 > 不能通过 useClass 在提供的类中使用 @Inject()

问题描述

我正在尝试ErrorHandler在我创建的子模块中用我自己的替换默认的 Angular。但是它抛出一个NullInjectorError.

我已经缩小了问题的范围以围绕@Inject(SENTRY_OPTIONS). 因为当我从中删除构造函数时,SentryErrorHandler它开始工作。

问题是。我想注入配置并且无法弄清楚我做错了什么,因为我似乎在做与docs相同的事情。

应用模块

@NgModule({
  // omitted...
  imports: [SentryModule.forRoot(environment.sentry)]
})
export class AppModule {}

哨兵模块

import {
  ErrorHandler,
  Inject,
  Injectable,
  InjectionToken,
  ModuleWithProviders,
  NgModule,
} from '@angular/core';
import { BrowserOptions, captureException, init } from '@sentry/browser';

const SENTRY_OPTIONS = new InjectionToken<BrowserOptions>('SentryOptions');

@Injectable()
export class SentryErrorHandler implements ErrorHandler {
  public constructor(@Inject(SENTRY_OPTIONS) config: BrowserOptions) {
    init(config);
  }

  public handleError(error: Error | any) {
    captureException(error.originalError || error);
    throw error;
  }
}

@NgModule()
export class SentryModule {
  public static forRoot(sentryOptions?: BrowserOptions): ModuleWithProviders {
    return {
      ngModule: SentryModule,
      providers: [
        { provide: SENTRY_OPTIONS, useValue: sentryOptions },
        { provide: ErrorHandler, useClass: SentryErrorHandler },
      ],
    };
  }
}

错误

Uncaught NullInjectorError: StaticInjectorError(AppModule)[ErrorHandler -> SentryErrorHandler]: 
  StaticInjectorError(Platform: core)[ErrorHandler -> SentryErrorHandler]: 
    NullInjectorError: No provider for SentryErrorHandler!
    at NullInjector.get (http://localhost:4200/vendor.js:36537:27)
    at resolveToken (http://localhost:4200/vendor.js:36864:24)
    at tryResolveToken (http://localhost:4200/vendor.js:36790:16)
    at StaticInjector.get (http://localhost:4200/vendor.js:36653:20)
    at resolveToken (http://localhost:4200/vendor.js:36864:24)
    at tryResolveToken (http://localhost:4200/vendor.js:36790:16)
    at StaticInjector.get (http://localhost:4200/vendor.js:36653:20)
    at resolveNgModuleDep (http://localhost:4200/vendor.js:58301:29)
    at _createClass (http://localhost:4200/vendor.js:58369:29)
    at _createProviderInstance (http://localhost:4200/vendor.js:58334:26)

标签: angulartypescript

解决方案


InjectionTokens显然必须导出:-/ 这有点不直观,因为它只在该文件中使用。

export const SENTRY_OPTIONS = new InjectionToken<BrowserOptions>('SentryOptions');
^^^^^^

推荐阅读