【发布时间】:2016-10-02 04:53:26
【问题描述】:
我有这个代码:
import {Injectable, ExceptionHandler, SkipSelf, Host, Optional} from '@angular/core';
import {ToastNotification} from '../toast-messages/toastNotification.service';
export class UIError extends Error {
constructor (private toastMessage: string) {
super();
this.toastMessage = toastMessage;
}
}
export class MyUIError extends UIError {}
export class AnotherError extends UIError {}
export class _ArrayLogger {
res = [];
log(s: any): void { this.res.push(s); }
logError(s: any): void { this.res.push(s); }
logGroup(s: any): void { this.res.push(s); }
logGroupEnd() {};
}
export class ConsoleLogger {
log(s: any): void {console.log(s);}
}
@Injectable()
export class CustomExceptionHandler extends ExceptionHandler {
constructor(private logger: ConsoleLogger, private toast: ToastNotification) {
super (new _ArrayLogger(), true);
}
call(exception: any, stackTrace = null, reason = null) {
let self = this;
if (exception.originalException instanceof UIError) {
self.toast.Error(exception.originalException.toastMessage);
} else {
this.logger.log(exception);
}
}
}
当我尝试运行它时,我遇到了 toast 的问题:ToastNotification。我得到的错误是:
zone.js:260Uncaught EXCEPTION: Error during instantiation of ApplicationRef_! (ApplicationRef -> ApplicationRef_).
ORIGINAL EXCEPTION: Cannot instantiate cyclic dependency! (ExceptionHandler -> ToastNotification)
ORIGINAL STACKTRACE:
Error: DI Exception
at CyclicDependencyError.BaseException
我也在 boostrap 中注入了这个组件。怎么解决?
【问题讨论】:
-
这是否意味着
ToastNotification作为ExceptionHandler作为构造函数参数? -
是的,它有一个 AppRef 的引用,在它的树中有一些 ExceptionHandler 组件 :( 处理这个问题的最佳方法是什么?
-
我想不要将
ExceptionHandler注入到ToastNotificationDI 无法应对循环依赖。对于构造函数注入,这在技术上是不可能的。您可以在 Angular 之外创建实例并强制解决循环依赖关系,方法是仅使用ToastNotification上的属性,其中ExceptionHandler在实例化后分配,然后使用provide(..., {useValue: ...})提供所有相关实例,但这非常难看。
标签: javascript angularjs dependency-injection typescript angular