Angular - How to resolve CanActivate deprecated in Angular-15 using Auth Guard

616 Views Asked by At

AuthGuard:

import { Injectable, inject } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, CanActivateFn, Router, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor(private route:Router){}
  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    if(localStorage.getItem('userdata')){
      return true;
    }else{
      this.route.navigate(['login'])
      return false;
    }
  }
}  

I got an error that

'CanActivate' is deprecated.ts(6385)
index.d.ts(302, 4): The declaration was marked as deprecated here.

How do I resolve this, and I want To deny access to a dashboard without a successful login and redirect users back to the login page

2

There are 2 best solutions below

0
Naren Murali On BEST ANSWER

You can use the canActivateFn equivalent of the same!

import { inject } from '@angular/core';
import { Router, CanActivateFn } from '@angular/router';

const AuthGuard: CanActivateFn = () => {
     const route = inject(Router);
     if(localStorage.getItem('userdata')){
         return true;
     }else{
         route.navigate(['login'])
         return false;
     }
};
0
NgDaddy On

Angular provideas standalone API CanActivateFn instaed of this:

Follow this guide: https://angular.io/api/router/CanActivateFn

Your case:

export const authGuard: CanActivateFn = (
  route: ActivatedRouteSnapshot,
  state: RouterStateSnapshot,
): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree => {
  const router = inject(Router);
  if (localStorage.getItem('userdata')) {
    return true;
  } else {
    return router.navigate(['login']);
    /** no need to return 'false', just return the promise */
  }
};

Or much simpler:

export const authGuard: CanActivateFn = () => {
  return !!localStorage.getItem('userdata') || inject(Router).navigate(['login']);
};

Example:

@Injectable()
class UserToken {
}

@Injectable()
class PermissionsService {
  canActivate(currentUser: UserToken, userId: string): boolean {
    return true;
  }
  canMatch(currentUser: UserToken): boolean {
    return true;
  }
}

const canActivateTeam: CanActivateFn =
    (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => {
      return inject(PermissionsService).canActivate(inject(UserToken), route.params['id']);
};

And a route:

{
      path: 'team/:id',
      component: TeamComponent,
      canActivate: [canActivateTeam],
}