I am using angular CanActivate Authguard interface to protect my component.
@Injectable()
export class AuthGuard implements CanActivate{
constructor(private router: Router, private authService: AuthenticationService) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | Observable<boolean> | Promise<boolean> {
this.authService.isLoggedIn.take(1).map((isLoggedIn : boolean) => {
if(!isLoggedIn){
this.router.navigate(['/login']);
return false;
}
return true;
})
this.router.navigate(['/login']);
return false;
}
}
i added it to my router configuration like this.
const appRoutes: Routes = [
{path : '',redirectTo : 'login',pathMatch : 'full'},
{ path: 'home', component: HomeComponent,canActivate : [AuthGuard] }
]
I also added it to providers array.
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
providers: [AuthGuard,
ExpenseService,SellDetailService,AuthenticationService],
styleUrls: ['./app.component.css']
})
But when i run the application its giving following error
StaticInjectorError(AppModule)[AuthGuard]:
StaticInjectorError(Platform: core)[AuthGuard]: NullInjectorError: No provider for AuthGuard!
I think i implemented it courrectly but its not working . what i am doing wrong???
AuthGuard is used to protect the routes from unauthorized access in angular. How AuthGuard Works? Auth guard provide lifecycle event called canActivate. The canActivate is like a constructor.
The canActivate guard checks if the user can visit the specific route or we have to prevent access to that specific route. We use the this guard when we have to check some condition and based on that users have the access to reach that specific route or not, before activating the component or showing it to the user.
You should add name of your guards to app.module in providers array Something like this
Providers:[AuthGuard]
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