The Angular application can be guarded using authguard service which allows to grant or restrict access to certain URL of the application.The main purpose of authguard service is to not to allow to directly hit URL without logged into the application we use authguard service.
There may be scenarios on the basis of which we restrict the user to navigate into the application, it may be the user must login (authenticate) first or may be the user has logged in but is not authorized to navigate to the particular component.
We have four different types of Guards:
can activate: it is used to check whether a user can visit a route.
CanActivateChild: it is used to check whether a user can visit a routes children.
can deactivate: it is used to check whether a user-user can exit a route.
Resolve: it is used to perform the route data retrieval before the route is activated.
CanLoad: it is used to see if a user can route to a module that lazy loaded.
To implement authguard service we use a CanActivate method, these are created as @Injectable classes.this return either true if the user can access a route or false if they can’t.
It can be used to return an observable or promise with API integration, This will keep the user waiting until the guard returns true or false.
Letscreate a simple CanActivate guard. Firstwe need to import the CanActivate interface ,:
letscreate an Injectable class called AppAuthGuard which implements the canActivate function:
Now we declare this created service in the
providerssection of ngmodule
Now in next step, we will add this authguard service to specific routes which we want to restrict user without permission
We have added our AppAuthGuard to the list of canActivate guards for this route to restrict the user to hit direct URL without permission