ActivatedRoute和AuthGuard-从paramMap获取ID的问题

时间:2019-05-22 12:22:38

标签: angular typescript

我目前正在开发一个用于考试项目的网站,但是我遇到了使用AuthGuard时代码未返回正确ID的问题。

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

  }

当我使用未过期的令牌登录时,我希望将ID 4记录在控制台中,并在这种情况下显示正确的事件。 当前,它显示为“ 0”。

1 个答案:

答案 0 :(得分:0)

您的路由配置中有两条相同的路由:

..
  {path: 'events/4', component: EventDetailsComponent, canActivate: [AuthGuard]},
  {path: 'events/:id', component: EventDetailsComponent},
..

具有4的第一条路线没有id参数。因此,当您打开此路线(<base_href>/events/4)时,将获得数字的默认值-0

因此,只需将4替换为:id并删除第二条路线。

更新

要仅对id === 4实施保护,请稍微更改canActivate方法:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

   const id = +route.paramMap.get('id');

   if(id !== 4)
    return true;

    ......
}