CanActivate и canLoad не работают после загрузки модуля
У меня есть приложения, которые загружают ленивый модуль. Как только модуль загружен, все компоненты также загружаются, и поэтому я не могу использовать его, может активировать для защиты отдельных компонентов лениво загруженного модуля. Есть ли способ, которым я могу лениво загрузить модуль, а затем защитить компонент после загрузки модуля
2 ответа
Решение
Have a look into the below code, Maybe it's useful for you.
This is my module routing example, which lazy loads.
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AuthGuard } from '../auth/auth-guard.service';
import { ModuleMainComponent } '...' // path
import { PathOneComponent } '...' // path
const demoRoutes: Routes = [
{
path: '',
component: ModuleMainComponent,
canActivate: [AuthGuard],
children: [
{
path: '',
canActivateChild: [AuthGuard],
children: [
{
path: 'path1', component:PathOneComponent,
canActivate: [AuthGuard]
}
]
}
]
}
]
@NgModule({
imports: [
RouterModule.forChild(demoRoutes)
],
exports: [
RouterModule
]
})
export class DemoRoutingModule { }
app.routes.ts
{
path: 'demo',
loadChildren: '....', // path of module
canActivate: [AuthGuard]
}
Это основные шаги, которые нужно выполнить при ленивой загрузке с помощью Auth Guard под углом.
в app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
/* Import child modules start */
import { Module1 } from './module1.module';
import { Module2 } from './module2.module';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
const routes: Routes = [
{ path: '', redirectTo: 'module1', pathMatch: 'full' },
{ path: 'module1', loadChildren: () => Module1 },
{ path: 'module2', loadChildren: () => Module2 },
{ path: '**', redirectTo: '404'},
{ path: '404', component: PageNotFoundComponent}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
в module1-routing.module.ts:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AuthGuard } from './../../core/guard/auth.guard';
import { AuthModule } from './auth/auth.module';
import { HomeLayoutComponent } from './../../layouts/home-layout/home-layout.component';
import { DashboardComponent } from './dashboard/dashboard.component';
const routes: Routes = [
{
path: 'module1, component: HomeComponent, canActivate: [AuthGuard]
children: [
{ path: '', 'dashboard', pathMatch: 'full' },
{ path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },
{ path: 'myapps', component: MyApplicationsComponent, canActivate: [AuthGuard] },
{
path: 'module1authmodule',loadChildren: () => AuthModule
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class Module1RoutingModule { }