Search code examples
javascriptangularangular-routingangular-router

How can I optimize code for canActive angular


how can I optimize that code, my co-worker told me that this code returns true and false, I already did it but, he said it not correct and told that I need recheck!

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    this.token = localStorage.getItem('JWT_TOKEN');
    if (!this.token) {
      return this.router.navigate(['mypage']);
    } else {
      return true;
    }
  }

Solution

  • If you prefer short, it is what you expected?

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
      this.token = localStorage.getItem('JWT_TOKEN');
      return !!this.token || this.router.navigate(['mypage']);
    }