#building a custom CanActivate guard where the condition is handled in the component

8 messages · Page 1 of 1 (latest)

worn sand
#

hey, i want to create a custom CanActivate guard where there's a specific logic that teh component itself decides, it's different the user is logged in guard, i want the componenents to impelment the interface ICanComponentActivate and defined their own canEnter method which has the logic, and i want to access it in the guard

this is the guard:

import {Injectable} from '@angular/core';
import {ActivatedRouteSnapshot, CanActivate, RouterStateSnapshot,} from '@angular/router';
import {Observable} from 'rxjs/internal/Observable';
import {of} from "rxjs";

export interface ICanComponentActivate {
  canEnter: () => Observable<boolean>;
}

@Injectable({
  providedIn: 'root',
})
export class CanActivateGuard
  implements CanActivate {

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot) :Observable<boolean>{
    const component = next.data?.component as ICanComponentActivate;
    return component.canEnter ? component.canEnter() : of(true);//this is where i have a problem
    //canEnter is alway undefined
  }
}

this is what i have on my route file:

{
  path: 'add',
  component: SomeComponent,
  data: {
    component:SomeComponent,
  },
  canActivate: [CanActivateGuard],
}

and this is how implemented it in my component

canEnter(): Observable<boolean> {
    return this.someData$.pipe(
      map((someData:ISomeData)=>!someData?.someField)
    );
  }

my issue is in the guard canEnter is always undefined

inland jay
#

That's not the component instance.

#

You cant get a hold of the component instance in canActivate afaik, only in canDeactivate.

worn sand
#

but i wanted it to be a generic thing that can be used elsewhere

#

in my case the data that i use for my condition is in a ComponentStore

inland jay
#

The only suggestion i have is, don't use the component.

inland jay