pheromix
pheromix

Reputation: 19327

How to pass data to the canActivate service guard?

There is routes definition :

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

How to pass data to the some_service ?

Upvotes: 0

Views: 745

Answers (2)

Zrelli Majdi
Zrelli Majdi

Reputation: 1260

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]}

Upvotes: 0

gil
gil

Reputation: 2552

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;

}

Upvotes: 2

Related Questions