简体   繁体   中英

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

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, should I use routing for this? But this will require me to import all components inside the app.module.ts or there is another way to use two app.module.ts one for the web and one for the admin?

Or what should I do?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM