Sam Ngugi
Sam Ngugi

Reputation: 1172

Route to different components when angular app starts

I have an angular app. When a user logs in, I want to display different UI based on user's role. A user can be just a customer or an admin

In my routing module I have the following

        {path: '', redirectTo: 'admin-portal' , pathMatch: 'full'},
        {path: 'admin-portal', component: AdminPortalComponent, canActivate: [AuthGuard]},
        {path: 'customer-portal', component: CustomerPortalComponent, canActivate: [AuthGuard]}

I want to be able to fetch a variable from local storage and use it to decide where I redirect the user when the app loads. I am thinking of having a condition like {path: '', redirectTo: 1===1 ? 'admin-portal' : 'customer-portal' , pathMatch: 'full'}

Upvotes: 0

Views: 224

Answers (1)

VithuBati
VithuBati

Reputation: 1928

You create another guard and put the conditions inside

    @Injectable()
    export class LoadGuard implements CanActivate {
      constructor(private router: Router) {

      }

      canActivate(next: ActivatedRouteSnapshot,
                  state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
        if(1===1){
           this.router.navigate(['admin-portal']);
           return false;
         }else{
           this.router.navigate(['customer-portal']);
           return false;
        }

      }
    }

and then in the route

{path: '', pathMatch: 'full',component: sampleComponent, canActivate: [LoadGuard]}

Upvotes: 2

Related Questions