Torsten Freyda
Torsten Freyda

Reputation: 31

Angular - Use Injector for Router in Service

I try to implement an error service which need to use the Angular Router methods in this class. And all I can found is to insert the Router class into my service by using Injector method of Angular.

So, I do grab the Injector object with dependency injection in my constructor of my serice class:

Import { ErrorHandler, Injectable, Injector } from '@angular/core';
import { Router } from '@angular/router';
 
@Injectable({
    providedIn: 'root'
})

export class RequestErrorHandlerService implements ErrorHandler {
 
    private _router: any

    constructor(
        private injector: Injector
    ) {}

    handleError(error) {

        const router = this.injector.get(Router);
        ...
        router.navigate(['/login']);   
    }
}

And I try to use injector.get() for to get the Router object. But all I get is an error

Uncaught TypeError: this.injector.get is not a function

So, I think I forgot something. But didn´t get the problem. Why does this not works?

Do have somebody a tip for me, or an link to a tutorial which realy works with Angular Version 8 or higher?

Thanks.

Upvotes: 2

Views: 4987

Answers (3)

Arutsudar Arut
Arutsudar Arut

Reputation: 513

Recently faced same issue, and had similar code that you had mentioned.

Check if you have mentioned the ErrorHandler in app module providers like below:

{
   provide: ErrorHandler,
   useClass: RequestErrorHandlerService
}

and not like below (Previously, in app module providers, when I had mentioned ErrorHandler as given below, it didn't work for me)

{
   provide: ErrorHandler,
   useClass: RequestErrorHandlerService,
   deps: [APP_INITIALIZER]
}

Anyways, below is some code snippets that worked for me, which might be useful.

app-error-handler.ts:

@Injectable()
export class AppErrorHandler implements ErrorHandler {

    constructor(private injector: Injector) {}

    handleError(error: Error) {
        console.log('Client side - ' + error.message);
        const router = this.injector.get(Router);
        router.navigate(['login']);
    }
}

app.module.ts:

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

Upvotes: 1

Emilien
Emilien

Reputation: 2761

Why not just like this ?

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

constructor(private router: router) {}

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

Upvotes: 0

Marek W
Marek W

Reputation: 729

You should be able to simply inject the Router via the constructor:

export class RequestErrorHandlerService implements ErrorHandler {
    constructor(
        private router: Router
    ) {}

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

Upvotes: 0

Related Questions