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
CanActivateChild
CanDeactivate
CanLoad
Resolve
The service injects AuthService and Router and has a single method called canActivate. This method is necessary to properly implement the CanActivate interface.
The canActivate method returns a boolean indicating whether or not navigation to a route should be allowed. If the user isn’t authenticated, they are re-routed to some other place, in this case a route called /login.
And finally, we need to add our guard in our routes:
constroutes:Routes= [ { path:'courses',loadChildren: () =>import('./courses/courses.module').then(m =>m.CoursesModule), canActivate: [AuthGuard] // This is an array because we can add multiple guards }, { path:'**', redirectTo:'/' }];