ovveriding ExceptionHandler时的循环依赖

时间:2016-06-02 12:36:48

标签: javascript angularjs dependency-injection typescript angular

我有这段代码:

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中注入了这个组件。怎么能解决这个问题?

2 个答案:

答案 0 :(得分:1)

看到这个问题How to Inject my service to ExceptionHandler后,我认为这可以解决您的问题。如果你控制一个循环依赖项的类,你可以将Injector注入构造函数,然后获取你想要的实例:

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

答案 1 :(得分:1)

在构造函数中使用注入器时,我仍遇到同样的问题。为我解决的是将注射部件移动到呼叫功能。

@Injectable()
export class AppExceptionHandler extends ExceptionHandler {
  private router:Router;
  private toaster:ToastsManager;

  constructor(private injector: Injector) {
    super(new _ArrayLogger(), true);
  }

  call(exception:any, stackTrace?:any, reason?:string):void {
    this.getDependencies();
    console.log(exception);

    if(exception.status === 401){
      // Show login
      this.router.navigate(['/login']);
    }

    // Get error messages if http exception
    let msgs = [];
    if(exception instanceof Response){
      msgs = this.getMessagesFromResponse(exception);
    }else{

      // Otherwise show generic error
      msgs.push('Something went wrong');
    }

    // Show messages
    msgs.forEach((msg) => this.toaster.error(msg));

    super.call(exception, stackTrace, reason);
  }

  private getDependencies(){
    if(!this.router){
      this.router = this.injector.get(Router);
    }
    if(!this.toaster){
      this.toaster = this.injector.get(ToastsManager);
    }
  }

}