Auth Service

Let's create an authentication service that will only redirect logged-in users to the dashboard.

We left off the last chapter with an issue related to our user dashboard. Our dashboard should only be viewable to users who are logged in. If they aren’t, they should be redirected to another view, such as /signup or /login instead.

To do this, we’ll create a route guard within Angular.

AuthGuard setup

First, we’ll create a guard within a new directory for our route guards.

ng g guard guards/auth/auth
Terminal 1
Terminal
Loading...

When running this command, there may be a prompt asking which type of interface we’d like to implement for the route guard. Select CanActivate if it isn’t already selected by default and hit enter.

In addition to creating the route guard, the CLI has created two new directories, src/app/guards and src/app/guards/auth, along with two files. This should be the terminal output:

CREATE src/app/guards/auth/auth.guard.spec.ts
CREATE
...