Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 RC 2 How to Inject Router into Custom ExceptionHandler

I'm using Angular 2 RC2. I need to inject the Angular 2 Router into my custom ExceptionHandler class. However I get the following error

Error: Error: Cannot resolve all parameters for 'ErrorHandler'(?). Make sure that all the parameters are decorated with Inject or have valid type annotations and that 'ErrorHandler' is decorated with Injectable.

I did try decorating private router: Router with @Inject to no avail. I'm using typescript, hence I don't think I need the @Inject attribute here.

My custom ExceptionHandler looks like this

import { ExceptionHandler } from '@angular/core';
import { Router } from '@angular/router';

export class ErrorHandler extends ExceptionHandler{

    constructor(
        private router: Router 
    ){
        super(null, null);

    }

    call(error, stackTrace = null, reason = null) {
        console.log(error);
        this.router.navigate(['/error']);
    }
}

My main.ts looks like this

import { bootstrap } from '@angular/platform-browser-dynamic';
import { AppComponent } from './app.component';

import { provide, ExceptionHandler } from '@angular/core';
import { ErrorHandler } from './error-handler/error-handler';

import { HTTP_PROVIDERS } from '@angular/http';
import { ROUTER_PROVIDERS } from '@angular/router';

bootstrap(AppComponent, [
    HTTP_PROVIDERS,
    ROUTER_PROVIDERS,
    provide(ExceptionHandler, {useClass: ErrorHandler})
]);

Why am I getting this error? Isn't the Router injectable when at the time of ExceptionHandler instantiation?

The complete source code is available here

https://github.com/harindaka/angular2-seed-typescript/tree/b368315ce6608085f3154a03bc53f0404ce16495

like image 963
Harindaka Avatar asked Jun 17 '16 10:06

Harindaka


1 Answers

See: ErrorHandler class. You can add Injectable decorator to achieve DI too!

import { ErrorHandler, Injectable } from '@angular/core';

@Injectable()
export class GlobalErrorHandler implements ErrorHandler {

  private myService: MyService;

  constructor(private injector: Injector) {
     this.myService = injector.get(MyService);
  }

  handleError(error) {
    alert('Bad things happening');
  }
  
}

@NgModule({
  providers: [
    {
      provide: ErrorHandler, 
      useClass: GlobalErrorHandler
    }
  ]
})
export class AppModule { }

Note: The above answers use ExceptionHandler which is removed in final release in favor of ErrorHandler.

like image 77
amcdnl Avatar answered Sep 28 '22 02:09

amcdnl