angular - 不能通过 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)
解决方案
InjectionTokens
显然必须导出:-/ 这有点不直观,因为它只在该文件中使用。
export const SENTRY_OPTIONS = new InjectionToken<BrowserOptions>('SentryOptions');
^^^^^^
推荐阅读
- python - 检测和测量熊猫数据框列中的模式
- c# - Xamarin Forms 和 xam.plugin.media:无法解析对 Xamarin.Essentials.Permissions 的引用
- android - 服务中的 Firebase Crashlytics 存在于库中构建的单独进程中
- c - 其中一个输出在一个简单的结构程序上显示(空)结果(没有结构数组)
- android - Flutter如何集成Admob?
- c++ - 将一个句子分成其单词的向量
- caching - STM32H7 MPU 可共享内存属性和强序内存类型
- r - 如何获得多个结果来运行观察函数?
- javascript - 如何最初将幻灯片容器设置为距左边距 10%,到达末尾时距右边距 10%?(vue-awesome-swiper)
- python - 尝试运行代码时代码挂起,电报机器人部署