How to separate admin and the front web in angular 2 project

后端 未结 1 567
抹茶落季
抹茶落季 2021-02-06 17:25

I\'m going to build a full project using angular 2, the project contains admin panel and a front-end web for users.

I don\'t know how to separate admin from the web, sho

相关标签:
1条回答
  • 2021-02-06 17:49

    I've built this recently and what I did was simply to split the routes into two different modules.

    So you'd have this:

    - +admin
      - routes
        - +dashboard
        - +login
        - ... etc
    - +website
      - routes
        - +home
        - +profile
        - ... etc
    

    Then what you want to do is use a canLoad guard to prevent modules from being loaded if you are not authorised to do so. This will protect the admin area in the frontend so that the code isn't exposed unless you're an admin with that privilege.

    This is the easiest way of doing it if you don't want to split the project into two smaller projects. Which I wouldn't do personally since sharing things across the apps becomes more complicated.

    EDIT:

    The routing would look like this:

    const routes: Routes = [
      {
        path: '',
        loadChildren: 'app/+website/website.module#WebsiteModule'
      },
      {
        path: 'admin',
        loadChildren: 'app/+admin-area/admin-area.module#AdminAreaModule'
      }
    ];
    
    @NgModule({
      imports: [
        RouterModule.forRoot(routes)
      ],
      exports: [
        RouterModule,
        AppComponent
      ],
      declarations: [
        AppComponent
      ]
    })
    
    export class AppRouterModule {}
    

    So simply going to /admin would load the admin area module, which would have another router module looking something like this:

    const routes: Routes = [
      {
        path: '',
        component: AdminAreaComponent,
        children: [
          {
            path: 'login',
            loadChildren: 'app/+admin-area/pages/+login/login.module#LoginModule'
          },
          {
            path: 'dashboard',
            loadChildren: 'app/+admin-area/pages/+dashboard/dashboard.module#DashboardModule',
            canLoad: [AuthGuardService]
          }
        ]
      }
    ];
    
    @NgModule({
      imports: [
        ComponentsModule,
        SharedModule,
        RouterModule.forChild(routes)
      ],
      declarations: [
        AdminAreaComponent
      ]
    })
    
    export class AdminAreaRouterModule {}
    

    Here you can see that /admin/dashboard is protected by a guard which checks the user's role.

    0 讨论(0)
提交回复
热议问题