5.2: Adding Router Guards
Right now anyone can access the members page (and any other site on our application) by typing in the url in their browser.
We need to protect these routes - and, for this we'll use a guard.
Adding Guards
We'll use the Angular CLI to generate auth.guard.ts
:
In the auth.guard.ts
file generated, update it to the following:
Add the AuthGuard as a service
In app.module.ts
, add AuthGuard to the providers array (and make sure it's imported at the top):
Adding AuthGuard to the Routes
We have a couple of different options here. We could add a guard to each component.
ex.
But, since all of our routes will have the same guard, this is a bit repetitive.
Perhaps a better method is to create a 'dummy route' - an empty route - and set all of our components we want to use this guard as its children.
Update routes.ts
to:
As we add more guards to our routes - it will be a lot cleaner to do it as in the example above.
Now all of our routes are protected.
Open your browser and verify that it is working as expected.
Last updated