Angular: Run canActivate on each route change

前端 未结 2 1142
后悔当初
后悔当初 2021-02-15 13:50

I got stuck recently with Angular route guards. CanActive runs only once when the page is loaded and does not run on route change within the guarded route. I think this was chan

2条回答
  •  你的背包
    2021-02-15 14:41

    The issue with subscribing to router events is that the navigation has already been started and the history has been updated, which makes it hard to prevent the navigation in a reliable way as a guard does.

    But Angular has learned to provide you with a way to configure how guards and resolvers should behave directly in your routes.ts:

    export const routes: Routes = [
      {
        path: '404',
        component: NotFoundComponent
      },
      {
        path: '',
        canActivate: [AuthGuard],
        runGuardsAndResolvers: 'always',
        children: [
           ....
        ]
      }
    ]
    

    Here's the docs: https://angular.io/api/router/RunGuardsAndResolvers

    There's a nice blogpost explaining your options: https://juristr.com/blog/2019/01/Explore-Angular-Routers-runGuardsAndResolvers/

提交回复
热议问题