Angular 角度路由器参数用破折号替换编码的空格
我已经在我的应用程序中定义了路由,其中一个是Angular 角度路由器参数用破折号替换编码的空格,angular,url,interceptor,angular-router,Angular,Url,Interceptor,Angular Router,我已经在我的应用程序中定义了路由,其中一个是'recipe-details/:name' const routes: Routes = [ ... { path: 'recipe-details/:name', component: RecipeDetailsComponent }, ... ]; 其中名称为uniqe,可以包括空格,例如name:“这是配方名称”。路由器对空间进行编码,因此我的url看起来像这样http://example.com/recipe-details/here%
'recipe-details/:name'
const routes: Routes = [
...
{ path: 'recipe-details/:name', component: RecipeDetailsComponent },
...
];
其中名称为uniqe,可以包括空格,例如name:“这是配方名称”
。路由器对空间进行编码,因此我的url看起来像这样http://example.com/recipe-details/here%20is%20recipe%20name
我想用破折号替换空格,使其看起来像这样http://example.com/recipe-details/here-is-recipe-name
。但我不想更改name param本身的值
我已尝试拦截UrlSerializer。当我在应用程序中导航时,它会工作。但当直接输入url时,它不起作用,因为paramname
具有带破折号的值这里是配方名称
,无法从数据库中读取(因为它不以这种形式存在)
有什么好主意吗?或者可能有其他方法来实现我的目标?解决方案是,当导航到路线时,必须显式添加破折号,然后在装载路线时再次删除破折号并添加空格 在您的情况下,在导航到路线之前,请执行以下操作:
navigateToRecipeDetails(name : String){
//Add dashes in place of spaces
let nameInRoute: String = name.split(' ').join('-');
this.router.navigate(['/recipe-details/'+ nameInRoute]);
}
现在,在配方详细信息组件中,在组件初始化中执行以下操作:
ngOnInit()
{
const routeParams = this.activatedRoute.snapshot.params;
//remove the dashes and add spaces
let name = routeParams.name.split('-').join(' ');
//this is your original recipe name which you had passed from previous page
}
您是否通过了
decodeURIComponent(您的\u编码的\u url)
Yes。这里我遇到的主要问题是,直接输入url不适用于上述解决方案。谢谢,但我认为有“更干净”的方法可以做到这一点。实际上,最好的做法是为这些内容创建slug,并将其保存在数据库中。这些段塞应用于布线。
ngOnInit()
{
const routeParams = this.activatedRoute.snapshot.params;
//remove the dashes and add spaces
let name = routeParams.name.split('-').join(' ');
//this is your original recipe name which you had passed from previous page
}