【问题标题】:How to have 2 routes with the same url in angular如何在 Angular 中有 2 条具有相同 url 的路由
【发布时间】:2020-06-24 00:43:24
【问题描述】:

使用 Angular 9 和 Angular 路由器。

我尝试关注以下主题:Angular 2 different components with same route

我想要实现的是有 2 条路由 '',如果通过身份验证,则移动到 privateModule,如果没有,则移动到 publicModule。

基本上,

如果我通过身份验证并转到www.myApp.com www.myApp.com

我设置了一个 app-routing.module.ts =>

const routes: Routes = [
  {
    matcher: publicMatcher,
    loadChildren: publicModule,
  },
  {
    matcher: privateMatcher,
    loadChildren: privateModule,
    canActivate: [AuthPrivateGuard],
    canActivateChild: [AuthPrivateGuard],
  },
]

然后我有 2 个匹配器,但我不知道如何设置它们。由于 url 是 '' 没有什么可以消费的,我目前有一个无限循环。

export function privateMatcher(segments: UrlSegment[]): UrlMatchResult {
  const key = localStorage.getItem('auth')
  if (key && JSON.parse(key).accessToken) {
    console.log('private')
    return { consumed: segments }
  }
  return null
}



export function publicMatcher(segments: UrlSegment[]): UrlMatchResult {
  const key = localStorage.getItem('auth')
  if (!key || !JSON.parse(key)?.accessToken) {
    console.log({ consumed: segments })
    return { consumed: segments }
  }
  return null
}

我可能用错了,或者不是实现我想要的好方法?

【问题讨论】:

    标签: angular routes


    【解决方案1】:

    我们可以通过this 方法实现同样的效果

    • 考虑到我想路由到 http://localhost:4200/home,创建一个包含私有、公共模块的 home 模块,在 app-routing 中定义这个公共模块的路由路径,如下所示。

    app-routing.module.ts

    const routes: Routes = [
     
        {
          path: 'home',
          loadChildren: () => import('./modules/home/home.module').then(mod => 
          mod.HomeModule)
        },
        ...
      ];
    

    home.module.ts

    import { NgModule } from '@angular/core';
    import { CommonModule } from '@angular/common';
    import { RouterModule, ROUTES, Routes } from '@angular/router';
    import { AuthService } from '../services/auth.service';
    @NgModule({
      declarations: [],
      imports: [
        CommonModule,
        RouterModule
      ],
      providers:[
        {provide:ROUTES,
        useFactory: configHomeRoutes,
      deps: [AuthService],
        multi: true}
      ]
    })
    export class HomeModule { }
    
    export function configHomeRoutes(authService: AuthService){
      let routes: Routes = [];
      if (authService.isAuthorized()) {
        routes = [
          {
            path: '', loadChildren: () => import('../private/private.module').then(mod => 
            mod.PrivateModule)
          }
        ];
      } else {
        routes = [
          {
            path: '', loadChildren: () => import('../public/public.module').then(mod => 
            mod.PublicModule)
          }
        ];
      }
      return routes;
    }
    

    private.module.ts

    @NgModule({
      declarations: [PrivateComponent],
      imports: [
        CommonModule,
        RouterModule.forChild([{path: '', component: PrivateComponent}])
      ]
    })
    export class PrivateModule { }
    

    public.module.ts

    @NgModule({
      declarations: [PublicComponent],
      imports: [
        CommonModule,
        RouterModule.forChild([{path: '', component: PublicComponent}])
      ]
    })
    export class PublicModule { }
    
    • homeModule 中 useFactory 提供程序使用的方法 homeRoutes 仅在我们第一次导航到 /home 路径时执行,这会导致加载第一次加载的模块。为了克服这个错误,我们必须删除Router中的/home路径并重新添加它,如下所示

    auth.service.ts

      public isAuthorized(): boolean {
        return this.authorizedSource.value;
      }
    
      public setAuthorized(value: boolean): void {
        const previous = this.authorizedSource.value;
        this.authorizedSource.next(value);
        if (previous === this.authorizedSource.value) {
          return;
        }
        const i = this.router.config.findIndex(x => x.path === 'home');
        this.router.config.splice(i, 1);
        this.router.config.push(
          {path: 'home', loadChildren: () => import('../../modules/home/home.module').then(mod => mod.homeModule)}
        );
      }
    

    【讨论】:

    • 您好,我查看了媒体链接和您的答案,并设法使某些东西即使不是完全干净也能正常工作。不过,这回答了问题,谢谢
    • 太棒了!中等链接确实有帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-05
    • 1970-01-01
    • 2017-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多