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

空扰寡人 提交于 2019-12-04 14:19:07

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/44226608/how-to-separate-admin-and-the-front-web-in-angular-2-project

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