JCAguilera
JCAguilera

Reputation: 976

Get route data with route url

I wanted to do a permissions system, where I saved what permissions a user has to have in order to access a certain URL.

Like this:

{ path: '/path/to/page', canActivate: [CustomGuard], data: {'permissions': ['can_edit','can_delete']}}

The Guard works fine, I can access the route data through there. But now I want to hide some items from the menu, based on these permissions.

So I was thinking about creating a method that recieves a url (/path/to/page) and then compare the user's permissions with the route permissions. Something like this:

canAccess(url: string) {
    const data = getRouteData(url); // I need this method
    return compare(this.userPermissions, data['permissions']) // true or false
}

But I still haven't found how to access the route data from a url. I really need help!

Upvotes: 1

Views: 1653

Answers (2)

Martin Nuc
Martin Nuc

Reputation: 5764

You can access routes array using Router:

  constructor(router: Router) {
    console.log(router.config);
  }

There you can read data attribute. However you this approach will not work for lazy loaded modules. Also you will have to match URL on your own.

Afaik there is no way to get this info from the router. Instead I would suggest you to implement permission system which can be used both by guards and by directives hiding/showing links.

Or use existing solution like ngx-permissions

Upvotes: 1

Lucho
Lucho

Reputation: 1547

What you can use then is a Resolver, basically what it helps you with is to before actually routing to the route, handle what ever you want to before actually rendering anything. So basically inject a Service to the resolver and then use the same service in the Menu component your using.

UPDATE

As discussed in comments what you can then in your guard is simply inject your permission service as following example (note the services in the constructor):

@Injectable()
export class AuthGuardService implements CanActivate {

    constructor(private userPermissions: PermissionService, private router: Router) { }

    canActivate() {


        if (compare(this.userPermissions.permissions, route.config.data.permissions) ) {

            return true;
        }

        return false;
    }

    private compare(userPermissions:any, routePermissions): boolean {
        // compare permissions and return true or false
    }
}

Then to read the permissions once routing is done, use Router service injected either to your component or service like this

@Component({
  selector: 'app-page1',
  templateUrl: './page1.component.html',
  styleUrls: ['./page1.component.css']
})
export class Page1Component implements OnInit {

  public permissions: Data;

  constructor(private route: Router) {
   }

  ngOnInit() {
    this.permissions = this.route.config[1].data.permissions;
  }

}

heres a stackblitz to view it in action

Upvotes: 1

Related Questions