遍历ExceptionHandler时的循环依赖 [英] Cyclic dependency , when ovveriding ExceptionHandler

查看:66
本文介绍了遍历ExceptionHandler时的循环依赖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码:

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);
        }
    }
}

当我尝试运行此命令时,我对吐司有疑问:ToastNotification。我得到的错误是:

When I try to run this, I have problem with toast: ToastNotification. The error I get is:

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中。

I inject this component in the boostrap also. How could this be solved?

推荐答案

看到此问题后如何将我的服务注入ExceptionHandler 我认为这可以解决您的问题。如果您控制循环依赖关系的类之一,则只需将 Injector 注入到构造函数中,然后获取您实际想要的实例:

After seeing this question How to Inject my service to ExceptionHandler I think this could be a solution for your problem. If you control one of the classes of the cyclic depenencies, you can just inject the Injector to the constructor and then acquire the instance you actually want:

constructor(injector:Injector) {
  setTimeout(() => this.someService = injector.get(SomeService));
}

这篇关于遍历ExceptionHandler时的循环依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆