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

人走茶凉 提交于 2019-12-03 09:02:05

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!