简体   繁体   English

Angular 2 Route params验证

[英]Angular 2 Route params validation

How can I validate Route params in Angular2? 如何在Angular2中验证Route params? For example, I have a route: 例如,我有一条路线:

{path: 'artist/:id', component: ArtistInfoComponent}

All I want is to check if parameter id is a valid number and if so, just show the component. 我想要的是检查参数id是否是有效数字,如果是,只显示组件。 Otherwise show a page with error message. 否则显示包含错误消息的页面。

I found Route Guards in Angular 2 but I think this isn't the best way to do validation because I can have many different params for different pages and writing individual Route Guard for all these pages isn't what I want. 我在Angular 2中找到了Route Guards,但我认为这不是进行验证的最佳方式,因为我可以为不同的页面设置许多不同的参数,并为所有这些页面编写单独的Route Guard不是我想要的。

Is there a possibility to specify a regex for each route parameter? 是否有可能为每个路由参数指定正则表达式?

UPD: Maybe there is a way to do a validation on query params? UPD:也许有办法对查询参数进行验证? I mean if I have such url: /search?q=blablabla&page=2 how can I check if the parameter page is valid? 我的意思是如果我有这样的网址: /search?q=blablabla&page=2如何检查参数page是否有效? Is there a way to do it without Guards? 没有卫兵有没有办法做到这一点?

防护是可行的方法,您可以将验证配置放入路径的data部分,并创建可重复使用的防护,以根据此配置验证参数。

By using ActivatedRoute service you can get the param and match the param in the lists of ids you have. 通过使用ActivatedRoute服务,您可以获取参数并匹配您拥有的ID列表中的参数。 If matches then show the details else show error message. 如果匹配则显示详细信息,否则显示错误消息。

exammple: exammple:

step 1: Inject(pass) ActivatedRoute in component constructor 步骤1:在组件构造函数中注入(传递)ActivatedRoute

constructor(private activtedRoute: ActivatedRoute){}

step 2: 第2步:

    constructor(private activtedRoute: ActivatedRoute){
     this.activtedRoute.paramMap.subscribe((params: ParamMap) => {
          const routeIdParam = params.get('id');
          if(this.validateId(routeIdParam)){
             // code to display info
                } else {
              // code to show error message!
             }   
           }

validateId(id): Boolean{
  return idArray.find(id); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM