【问题标题】:Angular Route Matcher Childrens Not LoadingAngular Route Matcher 儿童未加载
【发布时间】:2021-12-30 17:21:31
【问题描述】:

我正在尝试复制类似 Twitter 的 URL(即 @username)。据我所知,我可以使用matcher 而不是使用path 来实现它。到目前为止一切正常,但遗憾的是我无法使用matcher 访问我的子路由。它不是加载我定义的component,而是加载父组件。

我的代码: app-routing.module.ts

const routes: Routes = [
  {
    path: '',
    loadChildren: () => import('./home/home.module').then((m) => m.HomeModule),
  },
  {
    matcher: (url: UrlSegment[], group: UrlSegmentGroup, route: Route) => {
      if (!url || url.length === 0) {
        return null;
      }

      const pattern = new RegExp(/^@[\w]+$/gm);

      if (!pattern.test(url[0].path)) {
        return null;
      }

      return {
        consumed: url,
        posParams: {
          username: new UrlSegment(url[0].path.substr(1), {}),
        },
      };
    },
    loadChildren: () =>
      import('./profile/profile.module').then((m) => m.ProfileModule),
  },
  {
    path: 'post',
    loadChildren: () => import('./post/post.module').then((m) => m.PostModule),
  },
];

此路线可通过/@johnsmith 访问。现在我定义了另一个名为info 的路由,组件为ProfileInfoComponent

profile-routing.module.ts

const routes: Routes = [
  {
    path: '',
    component: ProfileComponent,
    children: [
           {
               path: 'info',
               component: ProfileInfoComponent,
  },
    ],
  },
];

其他变体

const routes: Routes = [
  {
    path: '',
    component: ProfileComponent,
  },
  {
    path: 'info',
    component: ProfileInfoComponent,
  },
];

但转到 /@johnsmith/info 会加载父组件 (ProfileComponent) 而不是 ProfileInfoComponent。有什么原因吗?

【问题讨论】:

  • 可能我错过了一些东西,但 /@johnsmith/info 应该 加载 ProfileComponent然后 加载 ProfileInfoComponent 因为 first 是 second 的父级。
  • @Dimanoid 是的,可能当我在children 中使用它时。实际上,我真的不想在那里使用它。这只是为了证明这两种变体都不起作用。实际的selector 也没有出现,只有ProfileComponent 的选择器。
  • 好吧 confs 看起来不错,很难说哪里出了问题。我可以建议打开路由跟踪,看看发生了什么angular.io/api/router/ExtraOptions#enableTracing
  • @Dimanoid 就我所见,通过追踪路线我并没有真正注意到任何事情。我猜这是因为路由是在其他模块中定义的。 components 在每条路线中都是 null,但仍显示正确的 component。我可以在这里发布完整的跟踪。

标签: angular typescript lazy-loading angular-routing angular-router


【解决方案1】:

我通过将 consumed: url 更改为 consumed: url.length === 1 ? url : url.slice(0, 1), 以某种方式使其工作

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-28
    • 1970-01-01
    • 1970-01-01
    • 2017-07-30
    • 2020-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多