23

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.

Bami
  • 383
  • 1
  • 4
  • 10

1 Answers1

13

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

sojin
  • 2,158
  • 1
  • 10
  • 18
  • 21
    That's more dodging the issue instead than actually fixing it. Angular 15 ships with a new `CanActivateFn` that one should implement: https://angular.io/guide/router-tutorial-toh#canactivate-requiring-authentication – J.P. Mar 13 '23 at 10:38
  • 2
    Thanks JP for the information – sojin Mar 15 '23 at 16:48