角路由器参数用破折号替换编码的空格

问题描述 投票:0回答:1

我已经在我的应用程序中定义了路由,其中​​之一是'recipe-details/:name'

const routes: Routes = [
...
  { path: 'recipe-details/:name', component: RecipeDetailsComponent },
...
];

其中名称为uniqe,可以包含空格,例如name: "here is recipe name"。路由器对空格进行编码,因此我的网址看起来像这样http://example.com/recipe-details/here%20is%20recipe%20name我想用破折号代替空格,看起来像是http://example.com/recipe-details/here-is-recipe-name。但是我不想更改名称参数本身的值。

我已经尝试拦截UrlSerializer。当我在应用程序中导航时,它可以工作。但是,当直接输入url时它不起作用,因为参数name带有破折号here-is-recipe-name,并且不能从数据库中读取(因为它不存在这种形式)。

@Injectable()
export class CustomUrlSerializerInterceptor implements UrlSerializer {
    private defaultUrlSerializer: DefaultUrlSerializer = new DefaultUrlSerializer();

    parse(url: string): UrlTree {
        return this.defaultUrlSerializer.parse(url);
    }    
    serialize(tree: UrlTree): string {
        return this.defaultUrlSerializer.serialize(tree).replace(/%20/g, '-');
    }
}

这里有个好主意吗?也许还有其他方法可以实现我的目标?

angular url interceptor angular-router
1个回答
0
投票

解决方案是,当您导航到路线时必须显式添加破折号,并在加载路线时再次删除破折号并添加空格。

根据您的情况,在导航至路线之前,请执行以下操作:

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
    }
© www.soinside.com 2019 - 2024. All rights reserved.