繁体   English   中英

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

[英]How to check a matching route that has params? ( in route guard)

我定义了一个路由,它有一个名为 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 不包含查询参数,因此它永远不会到达此代码块。

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

获取参数

您可以检查从组件或守卫中的“@angular/router”导入 ActivatedRouter 的路由参数。

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

然后将其注入构造函数并订阅参数。

constructor( private router: ActivatedRoute ) {
    this.router.params.subscribe( (params: any) => {
      console.log('params.yourParam');
    });
   }

然后你可以访问并使用参数来检查你需要什么。

编辑:

通过 canActivate 使用非常相似,您可以这样做:

(如果不需要可观察对象,也可以使用 ActivatedRouteSnapshot)

import { ActivatedRouteSnapshot, CanActivate } from '@angular/router';

在你的守卫课上得到这样的参数:

 canActivate( router: ActivatedRouteSnapshot ): boolean{

if ( Object.keys(router.params).length > 0 ){ 
    //then you have params

   if ( condition you need to check){
     return true
   } else { 
     return false;
   }

} else { 
     this.route.navigate(['/home']);
}

希望它能帮助你。

我实施的一种可能的解决方案是在路由器本身中创建一个没有参数的重定向并将其重定向到家。

{ 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");
}

我在路由中只有 id 参数,对于我的情况,我使用了 url 的替换函数

import { ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

   canActivateChild(route: ActivatedRouteSnapshot,
                    state: RouterStateSnapshot): Observable<boolean>|Promise<boolean>|boolean {
        const url: string = state.url.replace(/[0-9]/g, ':id');
        // if you have route like '/posts/post/5' this will return '/posts/post/:id'
        // your checking logic
   }

暂无
暂无

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

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