【问题标题】:Angular 9 routing based on first character of string基于字符串第一个字符的Angular 9路由
【发布时间】:2021-02-15 09:01:18
【问题描述】:

在我的 Angular 9 应用程序中,当路径以“@”开头时,我想导航到某个页面。

例如,“mywebsite.com/@sample-user”应该导航到用户组件,“mywebsite.com/@sample-user/:post-id”应该导航到 UserPostView 组件和“mywebsite.com/sample-user” (路径开头没有 @)应该导航到不同的组件。

const routes: Routes = [{path: '@:username', component: UserComponent}, {path: '@:username/:pist-id', component: UserPostViewComponent}, {path: 'sample-user', component: InternalComponent}]

我该怎么做?

【问题讨论】:

    标签: angular angular-routing


    【解决方案1】:

    我认为您可以为此使用带有正则表达式的自定义匹配器。

    RouterModule.forRoot([
     {
        matcher: (url) => {
          if (url.length === 1 && url[0].path.match(/^@[\w]+$/gm)) {
            return {
              consumed: url,
              posParams: {
                username: new UrlSegment(url[0].path.substr(1), {})
              }
            };
          }
          return null;
        },
        component: ProfileComponent
     }
    ])
    

    看看这篇文章,它有所有的答案。

    https://medium.com/@brandontroberts/custom-route-matching-with-the-angular-router-fbdd48665483

    【讨论】:

      猜你喜欢
      • 2020-07-02
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 2017-02-15
      • 1970-01-01
      • 1970-01-01
      • 2021-04-01
      相关资源
      最近更新 更多