javascript - Angular 2 Role based navigation on same path -


i've small question regarding angular 2 router using version 3.0.0-rc.1 want navigate different home component based on user role such admincomponent or usercomponent. can please in modifying below routes can achieve desired functionality?

{path: 'login', component: logincomponent},   <----this redirects '/' in case user logged in {   path: '',   component: homecomponent,                  canactivate: [authguardservice],  <-----check if user logged in, else redirect login   children: [     {       path: '',       component: admincomponent   <---- want navigate here if user role 'admin'     },     {       path: '',       component: usercomponent    <----- want navigate here if user role 'user'     }   ] } 

authguardservice.ts

import {injectable} "@angular/core"; import {canactivate, router, activatedroutesnapshot, routerstatesnapshot} "@angular/router"; import {authservice} "./auth.service";  @injectable() export class authguardservice implements canactivate {    constructor(private authservice: authservice, private router: router) {   }    canactivate(route: activatedroutesnapshot, state: routerstatesnapshot) {     if (this.authservice.isloggedin()) {       return true;     }      // store attempted url redirecting     this.authservice.redirecturl = state.url;      // navigate login page extras     this.router.navigate(['/login']);     return false;   } } 

authservice.ts

import {injectable} "@angular/core";  @injectable() export class authservice {   redirecturl: string;    logout() {     localstorage.clear();   }    isloggedin() {     return localstorage.getitem('token') !== null;   }    isadmin() {     return localstorage.getitem('role') === 'admin';   } } 

-thanks

the problem can't have 2 routes same path. easiest change can make change path this:

   {       path: 'admin',       component: admincomponent      },     {       path: 'user',       component: usercomponent     } 

this best option because since want components different based on user role. might want other components different , can adding children admin or user routes.

in authguard still return true, make 2 other guards admin , user routes. check if user or isn't admin.

and redirect correct route checking user role once loges in , in component router.navigate(['/admin']) or router.navigate(['/user'])


Comments

Popular posts from this blog

amazon web services - S3 Pre-signed POST validate file type? -

c# - Check Keyboard Input Winforms -