Home > other >  How to pass data to the canActivate service guard?
How to pass data to the canActivate service guard?

Time:05-10

There is routes definition :

{ path:'some_path', component: some_component, canActivate: some_service}

How to pass data to the some_service ?

CodePudding user response:

you can pass it this way:

first in your route definition add data property:

{ path:'some_path', component: some_component, canActivate: some_service, data: {routeData: <what ever you want to pass>}}

then in your some service guard you can access the data:

canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapshot ): Observable<boolean> {

    let routeData = route.data.routeData;

}

CodePudding user response:

First of all You should add a service implement CanActivate Interface:

import { CanActivate, Router, ActivatedRouteSnapshot } from "@angular/router";
import { Injectable } from "@angular/core";
@Injectable()
export class MyCustomRouteActivator implements CanActivate {
  constructor(private router: Router) {
    //You could inject a service has your currentUserData . . .  
  }
  canActivate(router: ActivatedRouteSnapshot) {
    //You could get data from router service like params //id username ....
    let canVisitPage = false;// add your conditional function here;
    if (!canVisitPage) {
      this.router.navigate([/404]);/ / choose your custom page path
}
  }
}

Then add this service to your app.module.ts :

providers:[....... MyCustomRouteActivator]

Finally You could use it on your route now:

//import MyCustomRouteActivator
{ path:'some_path', component: some_component, canActivate: [MyCustomRouteActivator]}
  • Related