angular - 从 url 获取 id,其中 param 位于路线 Angular 6 的中间
问题描述
我正在使用 Angular 6 和路由保护来保护应该:
- 检查以确保有登录用户(从存储中的 jwt 令牌获取用户对象。完成。
- 验证 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
.
解决方案
通过使用router.url
然后拆分它以获取 id 的简单方法
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];
}