路由角5中的破折号分隔参数破折号、路由、参数

2023-09-06 08:45:34 作者:心安勿忘

我想用破折号分隔 URL 中的参数,如下所示:

I want to separate my params in URL by dash like below:

localhost/add/5-ninja

这里的id是5,名字是ninja.当我将配置更改为此:路径:'/:id-:name'它不能正常工作.如何在 URL 中创建破折号分隔的参数

in here the id is 5 and the name is ninja. When i changed the config to this: path: '/:id-:name' It doesn't work properly. How can I create dash separated params in URL

推荐答案

我认为这不可能像你喜欢的那样,但我的建议是:

I think it's not possible the way you like but here's my suggestion to achieve that result:

在您的路线配置中,您声明路径:例如./:dashed

在你的组件中: in your routes config you declare the path: for ex. /:dashed

in your component:

import { ActivatedRoute } from '@angular/router';

class MyComponent {
constructor(private _route: ActivatedRoute) {
    const [id, name] = _route.snapshot.params.dashed.split('-');
    // you've got two variables 'id' and 'name' thanks to the array destructing
  }
}