路由嵌套 + 路由守卫

391 阅读1分钟

路由嵌套

一级路由:

  • index: 首页
  • user/index:用户中心 二级路由
  • user/center/info 用户中心 -> 我的信息
  • user/center/avatar 用户中心 -> 更改头像
  • user/center/security 用户中心 -> 安全管理 路由嵌套修改路由词典:
const routes = [
  {path:'index', component: IndexComponent},
  {
     path:'user/center',
     component:UserCenterComponent,
     children:[
       {path:'info',component:InfoComponent}
     ]
  }
]

注意:“用户中心”下的二级路由组件挂载点/路由出口应该放在UserCenter.component.html中

路由守卫

商业项目中,有些路由地址只能在特定条件下才能访问,例如用户中心页,只能在登录后访问

angular 提供了“路由守卫(Guard)”来实现访问路由组件前的检查功能

如果检查通过(return true)就放行;如果检查不通过(return false)就阻止访问

路由守卫(GUard)都是可注入的服务对象

使用路由守卫的步骤

  1. 创建路由守卫class -- 可使用 ng g guard 守卫名
@injecttable({provideIn:'root'})
export class LoginGuard implements CanActivate{
    canActivate(){
        return true  // 允许激活
        return false // 阻止激活
    }
}
  1. 在路由词典中使用守卫
{
    path:'ucenter', 
    component:UserCenterComponent,
    // 当前路由可以被激活吗?--- 应用路由守卫
    canActivate:[LoginGuard],
}