【问题标题】:Does angular support having multiple routes for a single path?角度是否支持一条路径有多个路径?
【发布时间】:2018-05-27 23:18:20
【问题描述】:

我希望将多个组件与根路径关联,以便为匿名用户显示一个登录页面视图,为经过身份验证的用户显示一个收件箱,而无需使用手动导航和路径更改拐杖。

我尝试使用这样的路由块启用我的场景:

{ path: '', component: LandingComponent, canActivate: [ ForbidAuthGuard ] },
{ path: '', component: LocationsComponent, canActivate: [ RequireAuthGuard ] }

Angular 确实在调用 ForbidAuthGuard,但在经过身份验证的用户上失败,因此完全取消了导航事件,忽略了 RequireAuthGuard 路由。

正如它们相互冲突的名称所暗示的那样,两个守卫是相互排斥的,因此只有一个路由会处于活动状态,但 Angular 似乎忽略了第二个路由。

这种机制是否可行?或者是否有任何其他技术可以实现第一段的最终目标?

为了完整起见,我将 @angular/router 和 @angular/core 与 5.2.8 版本一起使用。

【问题讨论】:

  • 有一种适当的方法可以实现您的目标,但它不是“具有与根路径关联的多个组件”。
  • @RandyCasburn 我想知道更多,你能详细说明一下吗?
  • 是的,因为你思想开放:-)。正确的方法是基于将身份验证抽象出来,这样它就可以正常工作并且不会影响您的日常开发。机制是API提供的HttpClient和HTTPIntercepter。您可以在此处找到文档:angular.io/guide/http#intercepting-requests-and-responses,其中有许多通过 Google 找到的示例。
  • @RandyCasburn 我确实有一个 http 拦截器来全局设置身份验证标头并处理隐式 oauth 令牌刷新,但我看不到它如何参与路由过程以确定哪个组件显示在屏幕。对不起。
  • 在拦截器中捕获 401/403 HTTP 状态代码并重定向到,如果未授权,可能是 LandingComponent,否则(如果尚未设置状态/如果首次访问)重定向到可能是 LocationsComponent跨度>

标签: angular


【解决方案1】:

你可以这样做:

{ path: '', component: MyService.DoACheck() ? LandingComponent, LocationsComponent },

但是那样就不会使用你的警卫了。

我假设,更常见的解决方案是您不想要的解决方案:

用警卫定义一条路线。

在该路由守卫中,确定用户是否可以访问该路由,如果不能,则导航到另一条路由。

像这样:

export  class AuthGuard implements CanActivate {

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

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        return this.checkLoggedIn(state.url);
    }

    checkLoggedIn(url: string): boolean {
        if (this.authService.isLoggedIn()) {
            return true;
        }

        // Retain the attempted URL for redirection
        this.authService.redirectUrl = url;
        this.router.navigate(['/login']);
        return false;
    }
}

【讨论】:

  • 我正在使用与此类似的方法,而有人帮助我实现了我真正想要的路由愿景。谢谢:)
  • 您是否考虑过向 Angular github 存储库发布问题/功能请求?
  • 很确定我遇到的这个问题只是由于我的知识有限,而不是由于 Angular 本身的问题。
【解决方案2】:

是的,您可以将多个组件关联到单个路由:

app.component.html

<div class="block">
  <div class="columns">
    <div class="column is-two-thirds">
      <router-outlet></router-outlet>
    </div>

    <div class="column">
      <router-outlet name="aux"></router-outlet>
    </div>
  </div>
</div>

路由配置

{
  path: 'my-single-url',
  children: [
    { path: '', component: ComponentOne },
    { path: '', component: ComponentTwo, outlet: 'aux' }
  ]
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-26
    • 2022-09-08
    • 2014-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-18
    相关资源
    最近更新 更多