Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error using router.navigate in Custom Error Handler

Hello I added a route navigation in my custom exception handler of Angular but I have the problem that when an error is triggered on the onInit of an Angular component it goes into an error loop:

Error: Cannot activate an already activated outlet

This is the code for my component:

    import { ErrorHandler, Injectable, Injector } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';

@Injectable()
export class ErrorService implements ErrorHandler  {

  constructor(
    private injector: Injector
  ) { }

  get router(): Router {
    return this.injector.get(Router);
  };


  handleError(error: any): void {
    console.error(error);
    this.router.navigate(['error', { error: error }], { skipLocationChange: true});
  }

}

And these my routes:

export const routes: Routes = [
  { path: '', redirectTo: 'browser', pathMatch: 'full' },
  { path: 'browser', loadChildren: './modules/browserui#BrowserUiModule' },
  { path: 'error', component: ErrorComponent, data: { title: 'Generic error' } },
  { path: '**', component: ErrorComponent, data: { title: '404 not found' } }
];

Any ideas? Thank you!

like image 248
Pedro José Peña Jerez Avatar asked Feb 28 '17 07:02

Pedro José Peña Jerez


1 Answers

@jonas and others, I actually found a better way to do this inside a global error handler. We don't even need a setTimeout which in my case that wasn't enough anyway, since it was partially routing (it was routing but portion of the previous page remained on the screen, kinda strange).

Anyhow, I found a GitHub post in the Angular repo, which says to use zone. So in my case I want to catch 401 and redirect to the login page and the code is as simple as this:

handleError(error: any) {
   console.error(error);
   if (error.status === 401) {
     zone.run(() => router.navigate(['/login']));
   }
}

Now it works as expected without any side effects.

like image 98
ghiscoding Avatar answered Oct 03 '22 23:10

ghiscoding