【问题标题】:Defining a route with unknown number of path in the middle定义中间路径数未知的路径
【发布时间】:2021-01-10 18:32:27
【问题描述】:

我有一个名为“articles”的路由,在路由的末尾我得到一个 id,但在中间我可以有一条路径,两条路径,更多甚至根本没有额外路径。

例如:

文章/111

article/publication/222

文章/出版物/书/555

有没有办法在不知道“文章”和 id 中间路径的确切数量的情况下定义这样的路线? 我只需要在组件中提取id,路径的其余部分我不感兴趣。

类似的东西-

const appRoutes: Routes = [
  
    { path: 'articles(/:param)*/:id',
        component: ArticlesComponent
    }
];

【问题讨论】:

  • 我没有找到类似的东西,但 Angular 的官方文档提到了通配符路线,即 /** 。试一试。不过我还没有测试过。
  • 我在 app-roting.module 中使用通配符路由,但在这里我想捕获以“articles”开头并以“id”结尾的特定路由
  • article/111 article/publication/222 article/publication/book/555 上述路由是否重定向到同一个组件?如果是这样,试试这个链接bennadel.com/blog/…

标签: angular typescript routes


【解决方案1】:

这不是一个解决方案,而是一个 hack。

如果/article/anything/anything/:id/article/:id 路由到同一个组件,那么 您可以为ArticleComponent 设置一个单独的路由模块,如下所示:

const routes: Routes = [
  {
    path: '',
    component: ArticleComponent
  },
  {
    path: '**',
    component: ArticleComponent
  }
];

由于我们使用了通配符路由,它将接受所有可能的路由。

如果你想获得最后一个路径,即 id,你可以从 ActivatedRoute 对象中获得,如下所示:

  constructor(
    private route: ActivatedRoute
  ) { 
      const paths = this.route.url.value
      const id = paths[paths.length-1].path
      console.log(id);
    }

【讨论】:

  • 谢谢!但是 id 对路由来说是强制性的,所以 path: '' 将只接受 'articles'
  • 你知道我为什么会收到这个错误“-错误 TS2339:属性'值'不存在于类型'Observable'。”我可以看到我可以访问“值”属性。
  • 需要做-this.route.url.subscribe(paths => { const id = paths[paths.length-1].path console.log(id); });
【解决方案2】:

您可以将“中间路由参数”定义为一个参数,它是一个逗号分隔的字符串,然后在解析该 URL 参数时拆分该字符串。

const appRoutes: Routes = [
  
    { 
        path: 'articles/:param/:id',
        component: ArticlesComponent
    }
];
this.route.paramMap.subscribe(params => {
 /// do something with params.get('id')
 /// do something with params.get('param')?.split(',')
})

【讨论】:

  • 不适用于 2 个中间参数.. 仅适用于一个。
  • 如果你像这样路由它不会工作:this.router.navigate(['articles', 'foo', 'bar', 'id']) 但如果你像这样路由this.router.navigate(['articles', 'foo, bar, as, many, items, as, you, want', 'id']),它会。
猜你喜欢
  • 2016-08-22
  • 1970-01-01
  • 2020-03-07
  • 2018-09-02
  • 2022-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-05
相关资源
最近更新 更多