Route guards

As in most web applications, there are resources (that is, pages/component templates) that are accessible to everyone (such as the Welcome page, Pricing page, About Us page, and other informational pages), and there are other resources that are only meant to be accessed by authorized users (such as a dashboard page and an account page). That's where route guards come in, which are Angular's way to prevent unauthorized users from accessing protected parts of our application. When someone tries to access a URL that is reserved for authorized users, he will typically be redirected to the public home page of the application.

In traditional web applications, the checks and validations are implemented in the server-side code and there is practically no option to validate whether the user can access the page at the client side. But using the Angular route guard, we can implement the checks at the client side without even hitting the backend services.

The following are the various types of guards available that we can use in our applications to enhance security for authorization:

  • CanActivate: Helps to check whether the route can be activated or not 
  • CanActivateChild: Helps to check whether the route can access child routes or not
  • CanDeactivate: Helps to check whether the route can be deactivated or not
  • Resolve: Helps to retrieve route data before activation of any route
  • CanLoad: Verifies whether the user can activate the module that is being lazy loaded

And before we jump into our hands-on exercise, I want to give you a quick overview of Angular route guards, such as where to use them, how to use them, what's the return type, and so on. Route guards are always injected as a service (that is, we have @injectable and we will need to inject it). The guards always return a Boolean value, true or false. We can make our route guards return the observables or promises, which internally get resolved into a Boolean value. 

We will continue to work on and expand the example we have created in the previous section. We are going to add a new component and call it CRUD. As a user, when you try to access the crud route, we will check when the route returns true. We will allow the user to navigate and see the template; otherwise, the application will throw an error prompt.

Let's dig right into the code to implement route guards. Just as we learned how to generate a component or a service, we can use the ng command and generate a route guard. In the Terminal, run the following command:

ng generate g activateAdmin

We have just generated a new route guard named activateAdmin. The output of the preceding command is displayed here:

Let's take a look at the files generated by the Angular CLI. Open the activate-admin.guard.ts file in the editor. Take a look at the default code generated in the file:

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs';

@Injectable({
providedIn: 'root'
})
export class ActivateAdminGuard implements CanActivate {
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean>
| boolean {
return true;
}
}

The first few lines are just importing the required CanActivate
ActivatedRouteSnapShot, and RouterStateSnapshot modules from the Angular router. Next, we know that since route guards are injectable, by using the @injectable 
decorator, we are informing Angular to inject it inside the root. And we are creating a class, ActivatedAdminGuard, that has a method already created inside it named canActivate. Note that this method has to return a Boolean value, either true or false. We have created our route guard, so now let's create a route now in our app-routing.module.ts file.

Take a look at the updated code of the app-routing.module.ts file:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { CrudComponent } from './crud/crud.component';
import { LoginComponent } from './login/login.component';
import { RegisterComponent } from './register/register.component';
import {ActivateAdminGuard } from './activate-admin.guard';

const routes: Routes = [
{ path: 'login', component: LoginComponent },
{ path: 'register', component: RegisterComponent },
{ path: 'crud', component: CrudComponent, canActivate:[ActivateAdminGuard] }

];

@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }

Note that in the routes, we have added the canActivate interface and, for our crud path, when we try to launch the crud route, since the canActivate method is returning true, the user will be able to see the component template.

Now, go ahead and set the value to false and find out what happens.

If you see the application's routing go back to base href, don't be surprised.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.156.25