无法通过useClass在提供的类中使用@Inject()

时间:2019-06-26 09:27:17

标签: angular typescript

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

我将问题范围缩小到@Inject(SENTRY_OPTIONS)。因为当我从SentryErrorHandler中删除构造函数时,它开始起作用。

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

AppModule

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

SentryModule

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)

1 个答案:

答案 0 :(得分:1)

InjectionTokens必须显然是:-/ 因为只在该文件内部使用,所以有点不直观。

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