Angular:在每次路由更改时运行 canActivate

标签 angular router canactivate

我最近被 Angular 路由守卫卡住了。 CanActive 仅在页面加载时运行一次,并且不会在 protected 路由内的路由更改时运行。我认为这已更改,因为它过去常常在每次更改时运行。根据我在论坛中阅读的内容,我应该使用 CanActivateChild。问题是,我们的应用程序由多个模块组成,这些模块有多个路由后代,当我在根模块中使用 CanActivateChild 时,它会在更改路由时被调用多次。

我觉得为每个子模块分配一个守卫是愚蠢的,因为对于 AppModule,那些延迟加载的子模块应该只是“黑盒子”,我想定义所有这些模块都应该被守卫。

export const routes: Routes = [
  {
    path: '404',
    component: NotFoundComponent
  },
  {
    path: '',
    canActivate: [AuthGuard],
    component: FullLayoutComponent,
    data: {
      title: 'Home'
    },
    children: [
      {
        path: 'administration',
        loadChildren: './administration/administration.module#AdministrationModule'
      },
      {
        path: 'settings',
        loadChildren: './settings/settings.module#SettingsModule'
      }
    ]
  },
  {
    path: '',
    loadChildren: './account/account.module#AccountModule'
  },
  {
    path: '**',
    redirectTo: '404'
  }
];

有什么解决办法吗?还是您认为这在安全方面“不是问题”?

谢谢大家

最佳答案

面对同样的问题,我在问题上所能找到的只是 Github 上一些已关闭的问题,Angular 开发人员声明这种行为“是设计使然”。

所以我最终做的是订阅 app.component 中的导航事件并在那里触发 AuthGuard 检查:

constructor(
  private router: Router,
  private route: ActivatedRoute,
  private authGuard: AuthGuard,
) {}

ngOnInit() {
  this.router.events
    .subscribe(event => {
      if (event instanceof RoutesRecognized) {
        this.guardRoute(event);
      }
    }));
}

private guardRoute(event: RoutesRecognized): void {
  if (this.isPublic(event)) {
    return;
  }

  if (!this.callCanActivate(event, this.authGuard)) {
    return;
  }
}

private callCanActivate(event: RoutesRecognized, guard: CanActivate) {
  return guard.canActivate(this.route.snapshot, event.state);
}

private isPublic(event: RoutesRecognized) {
  return event.state.root.firstChild.data.isPublic;
}

AuthGuard 相当标准:

@Injectable()
export class AuthGuard implements CanActivate{

  constructor(private auth: AuthService, private router: Router) { }

  canActivate(): Promise<boolean> {
    return this.auth.isLoggedInPromise()
      .then(isLoggedIn => {
        if (!isLoggedIn) {
          this.router.navigate(["/login"]);
        }
        return isLoggedIn;
      });
    }
  }

公共(public)路由应该这样配置:

{
  path: "login",
  component: LoginComponent,
  data: { isPublic: true }
}

这样实现的好处是默认情况下一切都受到保护,公共(public)路由应该明确配置,这将减少一些路由不 protected 可能性。还将其重构为某种服务,以便能够在多个应用程序中使用它。

灵感来自 this answer .

关于Angular:在每次路由更改时运行 canActivate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46805117/

相关文章:

angular - Angular 组件定义中的提供程序、更改检测、封装、主机

android - Cordova angular2应用程序中的"Exception: Error during instantiation of t! Primary outlet already registered."

javascript - 如何在加载组件 Angular 4 之前获得服务响应?

angular - 如何在Angular中对所有路由(主路由和所有子路由)应用canActivate守卫

http - Angular 2 : Rendering data from Observables

angular - Angular 如何确定路由的优先级 - 顶级与子级

angular - 将 Angular 4 与 GoJ 集成

javascript - Ember.js - 调用父模型 Hook 为子模型加载数据

javascript - 具有多个参数的主干路由器

javascript - Angular 2 中的 CanActivate 返回未定义