Angular Router and Route Protection
Angular Router is an official Angular routing library, written and maintained by the Angular Core Team.
It’s a JavaScript router implementation that’s designed to work with Angular and is packaged as @angular/router.
First of all, Angular Router takes care of the duties of a JavaScript router:
it activates all required Angular components to compose a page when a user navigates to a certain URL
it lets users navigate from one page to another without page reload
it updates the browser’s history so the user can use the back and forward buttons when navigating back and forth between pages.
In addition, Angular Router allows us to:
redirect a URL to another URL
resolve data before a page is displayed
run scripts when a page is activated or deactivated
lazy load parts of our application.
In this article, we’ll learn how to set up and configure Angular Router, how to redirect a URL and how to use Angular Router to resolve todos from our back-end API.
In the next article, we’ll add authentication to our application and use the router to make sure some of the pages can only be accessed when the user is signed in.
Route Protection
Angular comes with a number of baked-in features which are tremendously helpful for handling authentication. I think my favorite is probably its HttpInterceptor interface, but right next to it would be route guards. Let’s take a look at what Angular’s route guards are and how to use them to help with authentication in your Angular apps.
What are Route Guards?
Angular’s route guards are interfaces which can tell the router whether or not it should allow navigation to a requested route. They make this decision by looking for a true or false return value from a class which implements the given guard interface.
There are five different types of guards and each of them is called in a particular sequence. The router’s behavior is modified differently depending on which guard is used. The guards are:
CanActivate: Check if a user has access
CanActivateChild: Check if a user has access to any of the child routes
CanDeactivate: Can a user leave a page? For example, they haven’t finished editing a post
Resolve: Grab data before the route is instantiated
Lazy loading feature modules.
CanLoad: Check to see if we can load the routes assets
CanActivate
Guards are implemented as services that need to be provided so we typically create them as @Injectable classes.
Guards return either true if the user can access a route or false if they can’t.
They can also return an Observable or Promise that later on resolves to a boolean in case the guard can’t answer the question straight away, for example it might need to call an API. Angular will keep the user waiting until the guard returns true or false.
Lets create a simple CanActivate guard.
First we need to import the CanActivate interface, like so:
import {CanActivate} from “@angular/router”;
Then lets create an Injectable class called AlwaysAuthGuard which implements the canActivate function, like so:
class AlwaysAuthGuard implements CanActivate {
canActivate() {
console.log(“AlwaysAuthGuard”);
return true;
}
}
This guard returns true all the time, so doesn’t really guard anything. It lets all users through but at the same time our guard logs “AlwaysAuthGuard” to the console so we can at least see when it’s being used.
We need to provide this guard, for this example lets configure it via our NgModule, like so:
@NgModule({
.
.
providers: [
.
.
AlwaysAuthGuard
]
})
Finally we need to add this guard to one or more of our routes, lets add it to our ArtistComponent route like so:
const routes: Routes = [
{path: ”, redirectTo: ‘home’, pathMatch: ‘full’},
{path: ‘find’, redirectTo: ‘search’},
{path: ‘home’, component: HomeComponent},
{path: ‘search’, component: SearchComponent},
{
path: ‘artist/:artistId’,
component: ArtistComponent,
canActivate: [AlwaysAuthGuard],
children: [
{path: ”, redirectTo: ‘tracks’},
{path: ‘tracks’, component: ArtistTrackListComponent},
{path: ‘albums’, component: ArtistAlbumListComponent},
]
},
{path: ‘**’, component: HomeComponent}
];
IT Professionals, Web Developers, web programmers, IT students can Apply for the certification course and get ahead.