1

I'm trying to handle errors in Angular using Guards.

I have a role.guard that allows the user to get in certain paths depending on its role. I also have an auth.guard that does the same but depending on the authorization.

The role guard looks like this:

canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
    ): boolean {
        let res = route.data.role.includes(this.authService.getRole())
        if(!res){this.router.navigate(['/error'])}
        return res;
}

So far, the error component has the {{message}} property, which is declared in the error.component.ts.

I'd like this property to contain the error message depending on the Guard triggered (i.e. Unauthorized if role.guard is triggered, or, for instance, This page doesn't exist if I had a Component not found guard).

How could I achieve this? Is there a way to send a message from the Guard to the error component and display the corresponding error?

1 Answers1

0
  1. The first option is to use a query parameter and then subscribe to it inside the component. You will have an affected URL in this case.
  2. The second option is to add a new error service and register it inside the module. As a result, you will have one instance where you can add a property that will be shared between the guard and the error component.
export class RoleGuard implements CanActivate {
    constructor(private _service: ErrorService) {...}
    public canActivate(...) {
        this._service.sharedValue = "something happened";
        ...
    }
}

export class ErrorComponent {
    constructor(private _service: ErrorService) {...}
    public ngOnInit(): void {
        console.log(this._service.sharedValue);
    }
}
Anton Hirov
  • 191
  • 1
  • 5