【问题标题】:Angular 2 routing: match any path with a given prefixAngular 2 路由:匹配具有给定前缀的任何路径
【发布时间】:2019-01-19 22:14:15
【问题描述】:

我需要角度路由器来匹配以给定前缀开头的任何路径到组件。这是我的路由器配置。

  {
    path: 'posts/:id/:title',
    component: PostDetailsComponent
  }

当我使用router.navigate() 导航到类似/posts/1/json-web-token-(jwt)-authentication-with-asp.net-core-2.0 的路线时,一切正常,但一旦我尝试刷新页面,就会弹出一个错误

 Cannot match any routes. URL Segment: 'jwt'
   Error: Cannot match any routes. URL Segment: 'jwt'
    at ApplyRedirects.noMatchError (router.js:1719)

我已经尝试了推荐的解决方案here,但它似乎不适用于我的具体情况。我也尝试将我的路由器配置更改为:

  {
    path: 'posts/:id/**',
    component: PostDetailsComponent
  }

但这只是在构建时出错了。有什么方法可以匹配以/posts/:id/ 开头的任何路线吗?

【问题讨论】:

  • 您可以使用子路由来匹配您想要的方式

标签: angular typescript routing


【解决方案1】:

我想我偶然发现了一个解决方案。我从title 中删除了所有特殊字符,并用连字符替换了空格。这就是我的 url 生成逻辑的样子:

const cleanTitle = title.toLocaleLowerCase()
  .replace(/\s\s+/g, '-') // replace duplicate whitespace with hyphen
  .replace('(', '')
  .replace(')', '');
this.router.navigate([`/posts/${id}/${cleanTitle}`]);

此后,路由配置开始匹配像/posts/1/json-web-token-jwt-authentication-with-asp.net-core-2.0这样的url

【讨论】:

    【解决方案2】:

    如果你真的想在某个前缀之后匹配 any 路由,你需要在一个 special '**' catchAll 中使用子路线:

    {
        path: 'posts',
    //or with :id
    //  path: 'posts/:id',
        children: [
            {
              path: '**',
              component: PostDetailsComponent
            }
        ]
        
    }
    

    这将匹配带有“前缀”posts的所有路由,例如posts/8634986/json-in-urls-rockz-or-not或posts/my/path/is/longer/than/yours。 p>

    但是那样你会失去很多Angular Router的魔力:params等等。此外,它当然只适用于 valid(就 Angular 路由器认为是 valid 而言)URL。要实际访问 URL,您需要使用 Router.url。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-09
      • 1970-01-01
      • 1970-01-01
      • 2016-10-01
      相关资源
      最近更新 更多