1

It is possible to find many examples showing how to navigate between components using a button or a routerLink in angular 2. What I want to do is to navigate to a certain component when an error occurs, without user action. Like this:

class MyErrorHandler implements ErrorHandler {
    handleError(error) {
        this.router.navigate(['/pagenotfound']);
    }
}

But it is not possible to initialize a Router object in MyErrorHandler constructor. Is there any way to work around this issue and create an auto navigate system?

1

1 Answer 1

3

If you want to use the Router service inside your error handler class, you will have to inject it. You can do this by registering your service using the @Injectable decorator. See the example below.

@Injectable()
export class MyErrorHandler {
    constructor(private router: Router) {

    }

    handleError(error) {
        this.router.navigate(['/pagenotfound']);
    }
}

After doing this you can inject your MyErrorHandler service into your component or any other place you would like to use it.

For more information on dependency injection (DI), see: https://angular.io/guide/dependency-injection

Sign up to request clarification or add additional context in comments.

1 Comment

This helped me solve the problem but I had first to inject the injectible service and get the router via injectible. Thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.