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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With