1

Example: www.example.com/dashboard
I want to detect if user is Customer, it will load CustomerDashboardModule, if user is Staff, it's StaffDashboardModule, if user is Admin, it's AdminDashboardModule but the url is still /dashboard

Example code:

export const routes: Routes = [
{
    path: '',
    component: DashboardComponent,
    children: [
        {
            path: '',
            loadChildren: condition ? 'x' : 'y'
        }
    ]
}];

But it doesn't work.

Second problem is
How to detech User? Call an service of CoreModule. A solution is create a static property Injector in CoreModule and inject Injector in its constructor but I don't know if it's a good practice?

Steve Lam
  • 979
  • 1
  • 17
  • 40

1 Answers1

0

You can use a Guard that only when you have access to the route, you can navigate to the URL, when not, you can redirect to another URL.

Angular Router goto 'Milestone 5: Route guards'

Example define a guard in router config:

const routes: Routes = [
  {
    path: 'adminDashboard',
    component: AdminComponent,
    canActivate: [AdminAuthGuard],
    children: [
      {
        path: '',
        children: [
          { path: '', component: AdminDashboardComponent }
        ],
      }
    ]
  },
  {
    path: 'userDashboard',
    component: UserComponent,
    canActivate: [UserAuthGuard],
    children: [
      {
        path: '',
        children: [
          { path: '', component: UserDashboardComponent }
        ],
      }
    ]
  },
];

Guard example with redirect:

@Injectable()
export class AdminAuthGuard implements CanActivate {

auth: any = {};

constructor(private authService: AuthService, private router: Router) {}

canActivate() {
    if (/*user has privileges check*/) {
        this.router.navigate(['/adminDashboard']);
        return true;
    }
    else {
        this.router.navigate(['/userDashboard']);
    }
    return false;
  }
}

About your second problem, use a login to detect the logged in user and put the logic in a service for login handle and another service to check the user privileges that you have configured on the backend. If your application goes over the internet use https to send secure the user credentials.

G.Vitelli
  • 1,229
  • 9
  • 18
  • Thank you for your response, the problem is I want to keep the same url but load different module based on user type – Steve Lam Nov 19 '17 at 09:07