Search code examples
angularangular-routingangular8

Routes Based On User Roles


My app has three user types based on roles. I would like to use same url for all this users, allowing sharing of address. So using /ticker for user role client and /admin/ticker for user role admin is not a option.

However each combination of user role and model has a specific component. So I would like to bind the route /ticker to ClientTickerComponent if the user is a client and AdminTickerComponet is the user is an admin and SomethingTickerComponent if the client is a something.

The only solution I could figure out is use a TickerComponent in route and leave that to create the specific [Rule]TickerComponent based on the auth.


Solution

  • You can add routes dynamically to router

    In your app.component import Router

    import { Router } from '@angular/router';
    

    in constructor

    private router: Router
    

    in ngOnInit for each route to add

    let route = {};
    if (role === 'Client') {
        route = {
            path: 'ticker',
            component: ClientTickerComponent
        };
    }
    if (role === 'Admin') {
        route = {
            path: 'ticker',
            component: AdminTickerComponent
        };
    }
    
    this.router.config.unshift(route);
    

    Regards