Arturs Soms
Arturs Soms

Reputation: 489

How to Inject my service to ExceptionHandler

I used my service in other places injected automaticaly by angular 2. I want to use the same service in ExceptionHandler. But service doesn't post data to server. I went through debuger and my service invokes.

class MyExceptionHandler extends ExceptionHandler {
  rbJSLogger: RBLoggerService;

  constructor() {
    super(null,null);
    var injector = ReflectiveInjector.resolveAndCreate([
      RBLoggerService,
      JSONP_PROVIDERS,
      Http,
      ConnectionBackend,
      HTTP_PROVIDERS
    ]);
    this.rbJSLogger = injector.get(RBLoggerService);
  }
  call(error, stackTrace = null, reason = null){
    // console.error(stackTrace);
    this.rbJSLogger.searchBy("asd");
  }
}

Upvotes: 2

Views: 2141

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 658037

update ExceptionHandler was renamed to ErrorHandler https://stackoverflow.com/a/35239028/217408

orgiginal

This code

var injector = ReflectiveInjector.resolveAndCreate([...]);

creates a new independent injector that doesn't know anything about services provided in your Angular applications.

You might want to inject the injector used by Angular in your application like

class MyExceptionHandler extends ExceptionHandler {
  rbJSLogger: RBLoggerService;

  constructor(injector:Injector) {
    super(null,null);
    this.rbJSLogger = injector.get(RBLoggerService);
  }
  call(error, stackTrace = null, reason = null){
    // console.error(stackTrace);
    this.rbJSLogger.searchBy("asd");
  }
}

or just

class MyExceptionHandler extends ExceptionHandler {
  rbJSLogger: RBLoggerService;

  constructor(private rbJSLogger:RBLoggerService) {
    super(null,null);
  }
  call(error, stackTrace = null, reason = null){
    // console.error(stackTrace);
    this.rbJSLogger.searchBy("asd");
  }
}

Upvotes: 2

Related Questions