如何检查具有参数的匹配路线?(在路线守卫中)

我定义了一条路由,该路由具有一个称为uuid的查询参数


{path: 'is-protected/:uuid', component: protectedComponent, canActivate: [RouteGuardService]}

在路由防护中,我需要检查url是否匹配并且路由参数(:uuid)是否为空。如果路线没有参数,我需要将其重定向到本地路线。我正在尝试使用


if (state.url == 'is-protected'){

  if( query param exists){

    return true;

  }

  else {

      this.route.navigate(['/']);

  }

}

这不会起作用,因为state.url不包含查询参数,因此它将永远不会到达此代码块。


有没有办法检查包含参数的路线是否存在并进行相应导航?


慕田峪9158850
浏览 134回答 3
3回答

慕婉清6462132

我实现的一种可能的解决方案是在没有参数的情况下在路由器本身中创建重定向,并将其重定向到本地。{ path: 'is-protected', redirectTo: 'home', pathMatch: 'full' }如果查询参数不存在,这将处理。这种方法对我有用,因为我没有任何类似的路线或没有参数的路线。现在在路线守卫中if (state.url.indexOf('is-protected') > -1) {    //this route will have the query param. If it didnt, it would be redirected automatically because of redirection added in list of routes  if (condition I need to test) {    return true  } else {    this.route.navigate(['/home']);  }}如果有更好的方法或解决方案,请发表评论。谢谢!

慕慕森

您应该注入构造函数路由:ActivatedRouteSnapshot您可以像这样访问路线参数,并将其与您的期望值进行比较let id;if(route.paramMap.has('id')){    assessmentId = route.paramMap.get("id");}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript