Search code examples
angularangular7angular-router-guardsangular-guardsangular7-router

Angular7: Global Guard - CanDeactivate interface


I am very new to Angular, and was unsuccessful in finding an answer to what I am searching for.

The problem I am facing right now is that all the global error messages are not disappearing when I switch to another route.

I tried to solve this problem by using the CanDeactivate interface. This is my canDeactivate method:

  canDeactivate(): Observable<boolean> {
    console.log('delete test');
    this.globalMessageService.remove(GlobalMessageType.MSG_TYPE_ERROR);
    return of(true);
  }

This method is created in a Service called cms-page.guard.ts and by using this in specific pages, it seems to work just fine. Example if I use this in the "Courses" page:

const routes: Routes = [
  {
    path: 'courses',
    canActivate: [CmsPageGuards],
    canDeactivate: [CmsPageGuards],
    data: { pageLabel: 'courses' },
    component: CoursesPageComponent
  }
];

Basically, what I did is apply the canDeactivate method on a specific page. I was wondering if it is possible to create a Guard that applies globally the canDeactivate method, so it works for all pages when you change to another route?


Solution

  • I think your goal is to handle global errors. You don't need to use canDeactivateGuard for the same. You can achieve this by ErrorHandler interface.

    import { ErrorHandler, Injectable} from '@angular/core';
    @Injectable()
    export class GlobalErrorHandler implements ErrorHandler {
    constructor() { }
          handleError(error) {  //override handleError method
         //handle all errors here 
             console.log('error')
             // IMPORTANT: Rethrow the error otherwise it gets swallowed
             throw error;
          } 
    }
    

    Now just we need to tell angular to use GlobalErrorHandler instead of its default

    @NgModule({
    
    
     declarations: [AppComponent],
      imports: [BrowserModule],
      bootstrap: [AppComponent],
      providers: [
        {
          provide: ErrorHandler, 
          useClass: GlobalErrorHandler
        }
      ]
    })
    export class AppModule { }
    

    And for all components having declaration in app.module.ts, GlobalErrorHandler will be used. Hope it helps you!