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
Answers
You can use the
canActivateFn
equivalent of the same!Angular provideas standalone API
CanActivateFn
instaed of this:Follow this guide: https://angular.io/api/router/CanActivateFn
Your case:
Or much simpler:
Example:
And a route: