How To Add Authguard Service In Angular 5
Posted By : Shilpa Adlakha | 30-Apr-2018
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.
import { CanActivate } from "@angular/router";
Then
AppAuthGuard implements CanActivate {
canActivate() {
console.log("AppAuthGuard");
return true;
}
}
Now we declare this created service in the
@NgModule({
providers: [
AppAuthGuard
]
})
Now in next step, we will add this authguard service to specific routes which we want to restrict user without permission
const routes: Routes = [
{path: '', redirectTo: 'home', pathMatch: 'full'},
{path: 'find', redirectTo: 'search'},
{path: 'home', component: HomeComponent},
{path: 'about', component: AboutComponent},
{
path: 'about',
component: AppAuthGuard,
canActivate: [AppAuthGuard],
},
{path: '**', component: HomeComponent}
];
We have added our AppAuthGuard to the list of canActivate guards for this route to restrict the user to hit direct URL without permission
Thanks!
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Shilpa Adlakha
Shilpa is a bright Wordpress Developer, she has good knowledge of HTML, CSS, PHP and Wordpress.