请问在angular中如何一键给所有路由加全局守卫呢

来源:4-9 路由 URL 和参数(1)

会游泳的兔子先森

2020-10-25

{
    path: 'resource-edit',
    component: UploadComponent,
    data: {
      title: '编辑资源',
    },
    canActivate: [LoginGuard]
  },

因为每个路由我都需要加同样的守卫,如果在每个路由中都加canActivate太麻烦了,请问老师该如何写呢?求解答

router.beforeEach(async(to, from, next) => {})

像Vue这样就很方便

我暂时是用的暴力循环,不知道有没有更优雅的写法

const addGuards = (routes: Routes, name: string) => {
  routes.forEach((router: Route) => {
    if (!router.children) {
      router[name] = [LoginGuard]
    } else {
      addGuards(router.children, name)
    }
  })
}

addGuards(routes, 'canActivate')
写回答

1回答

接灰的电子产品

2020-10-25

在 ng 中,推荐的方式是在父路由上加上 CanActivateChild 这个守卫,这个路由之下的所有子路由都会被守护。

0
0

Angular 开发拼多多webapp 从基础到项目实战

高仿拼多多WebApp,带你在实战环境中学习Angular

1322 学习 · 451 问题

查看课程