【问题标题】:Angular - LazyLoading child-route starting with :id catches everythingAngular - 以 :id 开头的延迟加载子路由捕获所有内容
【发布时间】:2020-02-17 00:20:58
【问题描述】:

我有以下路由模块:

app-routing.modules.ts

...
const routes: Routes = [
  {
    path: '',
    loadChildren: () => import('./startpage/startpage.module').then(m => m.StartpageModule)
  },
  {
    path: 'user',
    loadChildren: () => import('./user/user.module').then(m => m.UserModule),
    canActivate: [AuthGuard]
  },
  {
    path: 'shop',
    loadChildren: () => import('./shop/shop.module').then(m => m.ShopModule),
    canActivate: [AuthGuard]
  },
  {
    path: '**',
    redirectTo: '',
    pathMatch: 'full'
  }
];
...

和 shop-routing.modules.ts

const routes: Routes = [
  {
    path: '',
    redirectTo: 'user',
    pathMatch: 'full',
  },
  {
    path: ':id',
    component: ShopPageComponent
  }
];

问题是,因为我用 ':id' 开始了 'shop' 的子路线,所以它充当了 'catch-everything' 路线。如果我现在调用'localhost:4200/user',它会加载 shopcomponent。为什么会这样?我认为 'shop' 是主要路线,并且仅当链接以 'shop/' 作为前缀时才调用 ':id' 子级。如果我之前输入 'shop/:id',它可以正常工作,但是该路线也可以通过 'localhost:4200/shop/shop/something' 调用,这很丑,而且我的 authGuard 也不再工作了。

【问题讨论】:

    标签: javascript angular routing


    【解决方案1】:

    App-routing.module.ts

    const routes: Routes = [
      {
        path: '',
        loadChildren: () => import('./startpage/startpage.module').then(m => m.StartpageModule),
        pathMatch: 'prefix'
      },
      {
        path: 'user',
        loadChildren: () => import('./user/user.module').then(m => m.UserModule),
        canActivate: [AuthGuard],
        pathMatch: 'prefix'
      },
      {
        path: 'shop',
        loadChildren: () => import('./shop/shop.module').then(m => m.ShopModule),
        canActivate: [AuthGuard],
        pathMatch: 'prefix'
      },
      {
        path: '**',
        redirectTo: '',
        pathMatch: 'full'
      }
    

    pathMatch: 'prefix' 将仅检查前缀路径并检查路径其余部分的子路径。

    【讨论】:

    • 请检查 shopModule 和 userModule 路径一次
    • "pathMatch: 'prefix'" 是救命稻草,但在这种情况下不是问题。经过无数小时的搜索,我发现了我的错误。我将“用户”模块导入到我的“主”模块中。删除它后,一切都像魅力一样工作。不过还是非常感谢!! :)
    • 我也导入了shop模块ofc并去掉了,忘了说。
    猜你喜欢
    • 2017-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-31
    • 2019-01-13
    • 2017-05-17
    • 1970-01-01
    相关资源
    最近更新 更多