Reputation: 71
I'm currently developing a website for an exam project, however I'm running into the issue of my code not returning the proper ID when I'm using my AuthGuard.
event-details.component.ts
getEvent(): void {
const id = +this.route.snapshot.paramMap.get('id');
this.eventService.getEvent(id)
.subscribe(event => this.event = event);
console.log(id);
}
app-routing.module.ts
{path: 'events', component: EventsComponent},
{path: 'events/4', component: EventDetailsComponent, canActivate: [AuthGuard]},
{path: 'events/:id', component: EventDetailsComponent},
admin.guard.ts
canActivate(): boolean {
console.log('In guard, canActivate() called');
var token = localStorage.getItem('token');
var key = localStorage.getItem('key');
var decodedtoken = this.jwtHelper.decodeToken(token);
console.log(decodedtoken);
var tokenExpired:boolean = this.jwtHelper.isTokenExpired(JSON.stringify(token));
console.log("tokenExpired was:" + tokenExpired);
if (key=='ACCEPTED'&&!tokenExpired)
return true;
else{
this.router.navigate(['/events']);
return false;
}
}
I'm expecting to get the id 4 logged in the console when I'm logged in with a non-expired token, as well as it displaying the right event in this case. Currently it shows "0" as output.
Upvotes: 1
Views: 973
Reputation: 745
You have two same routes in your routing configuration:
..
{path: 'events/4', component: EventDetailsComponent, canActivate: [AuthGuard]},
{path: 'events/:id', component: EventDetailsComponent},
..
First route with 4
does not have id
param. So when you open this route (<base_href>/events/4
) you will get default value for number - 0
So just replace 4
with :id
and remove second route.
UPDATE
To implement guard only for id === 4
, change your canActivate
method a little bit:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
const id = +route.paramMap.get('id');
if(id !== 4)
return true;
......
}
Upvotes: 1