代码之家  ›  专栏  ›  技术社区  ›  J.G.Sable

从url中获取id,其中param位于route Angular 6的中间

  •  0
  • J.G.Sable  · 技术社区  · 6 年前

    我正在使用Angular 6和route guard来保护一个编辑路由,它应该:

    1. 检查以确保有一个已登录的用户(从存储中的jwt令牌获取用户对象)。完成。
    2. 验证url参数中的id是否与令牌中用户的id匹配。

    我的路线是这样的 /members/:id/edit

    我已经有一个名为 doesUserIdInUrlMatchUserIdInToken 它将返回一个布尔值。

    我的auth guard canActivate函数是:

    export class UserEditAuthGuard implements CanActivate {
      constructor(
        private auth: AuthService,
        private activatedR: ActivatedRoute,
        private router: Router,
        private alertify: AlertifyService,
        private userService: UserService
      ) {}
    
      canActivate(): boolean {
        if (this.auth.loggedIn()) {
          console.log(this.activatedR.params["id"]);
          console.log(this.activatedR.snapshot.paramMap.get("id"));
          return true;
        }
    
        this.alertify.error("You shall not pass!!!");
        this.router.navigate(["/home"]);
    
        return false;
      }
    
      //   this.userService.doesUserIdInUrlMatchUserIdInToken();
    }
    

    这两个控制台日志都返回 null undefined .

    0 回复  |  直到 6 年前
        1
  •  1
  •   Abdulrahman Falyoun    6 年前

    通过使用 router.url 然后把它分开,得到身份证

    ID: any = null;
    constructor(router: Router) {
     console.log(router.url); // This will print the current url
     let URL = this.router.url;
     let URL_AS_LIST = URL.split('/');
     this.ID = URL_AS_LIST[1];
    }
    
    推荐文章