4

I have a multiple user Angular app, with a module for each user (because they have totally different accessible pages), like this:

  • app.module.ts
  • app-routing.module.ts
  • login/
    • login.component.ts
  • admin/
    • pages/
      • user-management/
      • configuration/
    • admin.module.ts
    • admin-routing.module.ts
  • user/
    • pages/
      • task-management/
      • configuration/
    • user.module.ts
    • user-routing.module.ts
  • guest/
    • pages/
    • guest.module.ts
    • guest-routing.module.ts

From the login page (/login from app-routing), I want to redirect to each module based on the credentials the user provided, but NOT with children routes like /user /admin or /guest

Instead, when an admin logs in, I want the URL to be reset. So, for example, the admin should not see the paths /admin/user-management or /admin/configuration; it just accesses /user-management or /configuration

Is this possible? Will it be a problem if I have a /configuration route for both admin and user?

EDIT: Here's a Stackblitz working example. Take a look at the URL routes when logged in.

EDIT 2: In the Stackblitz example, you can see the original problem on master and the working solution on solution branches.

GusSL
  • 652
  • 7
  • 23
  • You have to go and set up router guard ? – Developer May 04 '21 at 16:13
  • I have a `auth.guard.ts` implemented to restrict pages not accessible for users without the specific role, but the problem is with the URL route itself, not the access to it – GusSL May 04 '21 at 18:16
  • If role is admin then you can use canLoad, canActivate, guard, to not load URL – Developer May 04 '21 at 20:01
  • Can you provide an example? I already use canActivate to let the admin only access the admin routes, but that's not the issue. The issue is, whenever I load a routed submodule (`UserModule`, `AdminModule`, `GuestModule`), I have to do it under a subroute (`/users` `/admin` `/guest` respectively). But I don't want that behavior. I want to load a submodule and use its routes under the root route (`/`) – GusSL May 06 '21 at 01:57
  • Then put all this sub modules to parent path, it will load as a parent @GusSL – Developer May 06 '21 at 03:20
  • What is wrong with showing user, admin and guest? – Robin Dijkhof May 07 '21 at 12:32
  • @RobinDijkhof because it adds unnecessary length to the URL. A user with a role is not intended to be routed to the other user roles' pages. And as the submodule grows and the nested routes increase, it is annoying to see a `/admin` displayed prefixed to all the routes the admin will interact with. – GusSL May 07 '21 at 15:40
  • Note that hiding URLs is not a secure solution. Other than aesthetics, this is not a useful feature. – Robin Dijkhof May 07 '21 at 15:56
  • Indeed, I also think this feature is more focused on URL aesthetics. Using guards complement the security part. – GusSL May 07 '21 at 16:26

2 Answers2

5

SOLUTION:

After a lot of investigation, I found out that it can be done with creating a route matcher.

CODE:

I managed to make it work with your code. Here is the working example: https://stackblitz.com/edit/angular2-routing-test-qj4geu?file=src/app/user/user.component.html

This is the relevant code on app-routing.module.ts:

const routes: Routes = [
  {
    path: 'login',
    component: LoginComponent
  },
  {
    matcher: url => {
      const user_type = localStorage.getItem('user_type');
      if (user_type === 'user') {
        return url.length ? { consumed: [] } : { consumed: url };
      }
      return null;
    },
    loadChildren: () => import('./user/user.module').then(m => m.UserModule)
  },
  {
    matcher: url => {
      const user_type = localStorage.getItem('user_type');
      if (user_type === 'admin') {
        return url.length ? { consumed: [] } : { consumed: url };
      }
      return null;
    },
    loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule)
  },
  {
    matcher: url => {
      const user_type = localStorage.getItem('user_type');
      if (user_type === 'guest') {
        return url.length ? { consumed: [] } : { consumed: url };
      }
      return null;
    },
    loadChildren: () => import('./guest/guest.module').then(m => m.GuestModule)
  },
  {
    path: '',
    pathMatch: 'full',
    redirectTo: 'login'
  }
];

NOTE:

As stated here: https://github.com/angular/angular/issues/23866#issuecomment-388527483, when we use route matcher we need to specify which portion of the url was consumed by the matcher function, and the remaining portion will be send to the nested router.

BLOGS:

Here are two blog posts that has in-depth details and walk-through how to do it:

Blog 1: https://medium.com/@brandontroberts/custom-route-matching-with-the-angular-router-fbdd48665483

Blog 2: https://medium.com/@lenseg1/loading-different-angular-modules-or-components-on-routes-with-same-path-2bb9ba4b6566

NeNaD
  • 18,172
  • 8
  • 47
  • 89
  • The problem is that the module `admin` is loaded under the `/admin` route, and all the subroutes append `/admin`. Please take a look at the Stackblitz in the updated question. – GusSL May 06 '21 at 20:27
  • The main routing works as intended! It seems that localStorage is the way to go, for not having to inject the global auth service. One thing though, the subroutes stopped working, even entering then manually in the URL. It seems it is not matching any of the subroutes when logged in and just jumps into the last one (`''`) in the submodules routing module. – GusSL May 07 '21 at 06:57
  • After a few more hours of investigating, I solved that bug with a few lines of code. I updated the working example, and now all the sub-routes will work also. Can you check it? – NeNaD May 07 '21 at 10:02
  • It works nicely! However, I improved a little the solution to make it less repetitive, making the module selection in one single custom-matched route, but essentially it is the same as yours. Thank you very much! – GusSL May 07 '21 at 14:39
  • 1
    Hey, I saw you suggested edit. Nice idea to put everything to one route `matcher`. But, the code you suggested didn't work when I tried it. It works first time when user logs in, but if you logout and log in again as the other user with different type, the module of previous user will be loaded. Check it here: https://www.loom.com/share/f9477b5c08b44652b1603c0a999d03ce – NeNaD May 07 '21 at 19:26
  • I updated the answer with current code in `app-routing.module.ts`. We can update it with one route `matcher` once we make it work for multiple logins by user with different types. – NeNaD May 07 '21 at 19:41
  • I just realized that and I kinda know why that happens. When logging in, a module is lazy-loaded, but when logging out and in again, the loaded module is still associated with the `/` route. While it seems one can destroy a module (see https://github.com/angular/angular/issues/24962), a quick workaround is to reload the window when logging out to "unload" all sub-modules. I see it convenient, since it won't be very common to see users changing back and forth between accounts. You can see the updated `solution` branch here: https://stackblitz.com/edit/angular2-routing-test – GusSL May 08 '21 at 00:51
1

I gues your use lazy loading configuration looks something like this:

  {
    path: 'config',
    loadChildren: () => import('./pages/userConfig/userConfig.module').then( m => m.UserConfigPageModule),
  },

You can convert the arrow function into a normal function and do e.g. an switch statement to deside what module you want to load:

  {
    path: 'config',
    loadChildren: () => {
      switch(userType) {
        case 'IsAdmin':
          return import('./pages/adminConfig/adminConfig.module').then( m => m.AdminConfigPageModule);
        case 'IsUser':
          return import('./pages/userConfig/userConfig.module').then( m => m.UserConfigPageModule);
        default:
          return import('./pages/guestConfig/guestConfig.module').then( m => m.GuestConfigPageModule);
      }
    },
    canActivate: [ConfigGuard],
  },

Working stackblitz

Note:
After logout you need to refresh the stackblitz view otherwise it kinda glitches. I'll look into it later.

Norbert Bartko
  • 2,468
  • 1
  • 17
  • 36
  • 1
    This could be the solution. I use a BehaviorSubject in a global service to get the current user. How could I inject the service inside of the app-routing.module where I declare the routes? Also, please take a look at the Stackblitz, I updated the question. – GusSL May 06 '21 at 20:25
  • @GusSL check out the stackblitz – Norbert Bartko May 07 '21 at 08:24
  • 1
    It works, but when logged out and in again, it loads the last module. Anyway, the switch case idea helped a lot to build the final answer above. Thanks! – GusSL May 07 '21 at 14:26