Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - How to resolve CanActivate deprecated in Angular-15 Auth Guard [duplicate]

Tags:

angular

I upgraded my Angular-14 code to Angular-15. Then I have this code:

AuthGuard:

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { ToastrService } from 'ngx-toastr';
import { AuthService } from 'src/app/features/auth/services/auth.service';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {

  constructor(private authService: AuthService, private toastr: ToastrService, private router: Router) { }
  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ):
    | Observable<boolean | UrlTree>
    | Promise<boolean | UrlTree>
    | boolean
    | UrlTree {
    if (!this.authService.isLoggedIn()) {
      this.toastr.info('Please Log In!');
      this.router.navigate(['/auth']);
      return false;
    }
    // logged in, so return true
    this.authService.isLoggedIn();
    return true;
  }
}

Then I got this error:

CanActivate is deprecated

How do I resolve this?

Thanks.

like image 404
Bami Avatar asked Sep 09 '25 10:09

Bami


1 Answers

Note: This answer is no more valid with latest versions of angular

You don't need to implement CanActivate any more

Angular detail description

@Injectable({
  providedIn: 'root'
})
export class AuthGuard {

  constructor(private authService: AuthService, private toastr: ToastrService, private router: Router) { }
  canActivate():
    | Observable<boolean | UrlTree>
    | Promise<boolean | UrlTree>
    | boolean
    | UrlTree {
    if (!this.authService.isLoggedIn()) {
      this.toastr.info('Please Log In!');
      this.router.navigate(['/auth']);
      return false;
    }
    // logged in, so return true
    this.authService.isLoggedIn();
    return true;
  }
}

Please note: This is a temporary solution for those who are upgrading from older version

please read https://angular.io/guide/router-tutorial-toh#canactivate-requiring-authentication for permanent updates

like image 185
sojin Avatar answered Sep 11 '25 06:09

sojin