代码之家  ›  专栏  ›  技术社区  ›  User 5842

根据当前可用路由列表激活第一个子路由

  •  0
  • User 5842  · 技术社区  · 8 年前

    假设我的角度应用程序中有以下路由结构:

    children: [
        {
            component: Access,
            path: 'access'
        },
        {
            component: Authentication,
            path: 'authentication'
        },
        {
            component: Domains,
            path: 'domains'
        },
        {
            component: Recovery,
            path: 'recovery'
        },
        {
            path: '**',
            pathMatch: 'full',
            redirectTo: 'authentication'
        }
    ]
    

    authentication 路径,这将始终是当前选定的路径。但是,我的应用程序中有不同的用户具有不同的访问策略,有些用户无法访问 身份验证 access 路线。

    能不能不用硬编码 身份验证

    完全管理

    自定义管理

    我想要 Access 成为第一个被选中的(活动的),因为它是子列表中第一个可用的。

    可能是一个自定义的解析器或守卫来决定在运行时,所述用户是否 Full Custom

    谢谢

    1 回复  |  直到 8 年前
        1
  •  0
  •   Phil    8 年前

    这听起来像是路由守卫的完美用例。例如,在这里检查如何实现一个:

    https://medium.com/@ryanchenkie_40935/angular-authentication-using-route-guards-bf7a4ca13ae3

    简而言之:

    @Injectable()
    export class AuthGuardService implements CanActivate {
      constructor(public auth: AuthService, public router: Router) {}
      canActivate(): boolean {
        if (!this.auth.isAuthenticated()) {
          this.router.navigate(['access']);
          return false;
        }
        return true;
      }
    }
    

    import { 
      AuthGuardService as AuthGuard 
    } from './auth/auth-guard.service';
    // ...
    {
        component: Authentication,
        path: 'authentication',
        canActivate: [AuthGuard]
    },
    
    推荐文章