J.G.Sable
J.G.Sable

Reputation: 1408

Getting id off url where param is in middle of route Angular 6

I'm using Angular 6 and a route guard to protect an edit route that should:

  1. Check to make sure there is a logged in user (getting the user object from the jwt token in storage. Done.
  2. Verify that the id in the url parameter matches the id of the user in the token.

My route is something like this /members/:id/edit

I already have a function called doesUserIdInUrlMatchUserIdInToken which will return a boolean.

my auth guard canActivate function is this:

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();
}

both of these console logs are returning null and undefined.

Upvotes: 2

Views: 1474

Answers (1)

Falyoun
Falyoun

Reputation: 3976

Simple way for doing that by using router.url and then split it to get the 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];
}

Upvotes: 2

Related Questions