Wr4*_*i7h 3 typescript angular angular6
如何仅在开发模式下加载某些路由。当我在启用生产模式的情况下构建时,我希望禁用这些路由。
有人对如何实现此功能有什么好的建议吗?例如,如果处于开发模式,则隐藏下面的route2组件。
const routes: Routes = [
{
path: '',
component: AdminComponent,
canActivate: [AuthGuard],
runGuardsAndResolvers: 'always',
data: { allowedRoles: ['Role1','Role2'] },
children: [
{
path: '',
redirectTo: 'dashboard/main',
pathMatch: 'full'
},
{
path: 'route2',
loadChildren: './theme/route2/route2.module#route2Module'
}
]
}
Run Code Online (Sandbox Code Playgroud)
根据您的 Angular Router 代码:
const routes: Routes = [
{
path: '',
component: AdminComponent,
canActivate: [AuthGuard],
runGuardsAndResolvers: 'always',
data: { allowedRoles: ['Role1','Role2'] },
children: [
{
path: '',
redirectTo: 'dashboard/main',
pathMatch: 'full'
},
{
path: 'route2',
loadChildren: './theme/route2/route2.module#route2Module'
}
]
}
Run Code Online (Sandbox Code Playgroud)
您正在尝试使用路由器实现延迟加载,并且还启用仅针对开发环境加载特定模块(如果我的理解是正确的)。为此 Angular Router 提供了一个名为CanLoad的Guard。当您不想为了延迟加载而将特定模块加载到路由时,CanLoad 就可以发挥作用。CanActivate 是否用于组件级防护,但在这种情况下会将模块加载到浏览器。
所以将代码改成这样:
const routes: Routes = [
{
path: '',
component: AdminComponent,
canActivate: [AuthGuard],
runGuardsAndResolvers: 'always',
data: { allowedRoles: ['Role1','Role2'] },
children: [
{
path: '',
redirectTo: 'dashboard/main',
pathMatch: 'full'
},
{
path: 'route2',
loadChildren: './theme/route2/route2.module#route2Module', // Don't want to load this module
canLoad: [DevEnvGuard]
}
]
}
@Injectable()
class DevEnvGuard implements CanLoad {
constructor() {}
canLoad(route: Route, segments: UrlSegment[]): Observable<boolean>|Promise<boolean>|boolean {
return !environment.prod; // if prod = false it will load module
}
}
Run Code Online (Sandbox Code Playgroud)
我认为这就是方法。如果我遗漏了什么,请在评论中告诉我。
| 归档时间: |
|
| 查看次数: |
4307 次 |
| 最近记录: |