Which Guard fired GuardsCheckEnd?

977 Views Asked by At

We have a few router guards that protect different parts of our app.
In some cases, but not in all, we want to do things when the guard returns false.

router.events.subscribe(event => {
  if (event instanceof GuardsCheckEnd){
    if (!event.shouldActivate){
      //do stuff
    }
  }
});

The above code checks if any guard failed. We want to //do stuff only when a specific guard failed.
Is there a way to find out which guard failed?

1

There are 1 best solutions below

1
On BEST ANSWER

From what I understand you want to know which guards fail, so you should record their value in guard service. This way it will be available to you at all times.

First guard

// FirstGuard
constructor(private guardService: GuardService) {}

canActivate() boolean {
  const canActivate = //some logic
  this.guardService.set('firstGuard', canActivate);
  return canActivate;
}
export class GuardService {
  private data = {};

  public set(guardName: string, value: boolean): void {
    this.data[guardName] = value;
  }

  public get(guardName: string): boolean {
    return this.data[guardName] ?? false; // choose default
  }

  public clear(): void {
    this.data = {};
  }
}

Where this interests you

router.events.subscribe(event => {
  if (event instanceof GuardsCheckStart) {
    // Make sure you don't have results from past events
    this.guardService.clear();
  }
  if (event instanceof GuardsCheckEnd){
    if (!event.shouldActivate){
      if (this.guardService.get('firstGuard')) {
        // do stuff
      }
    }
  }
});