TubeSort Extras
You're not Alone!

We're here to help you to fight your YouTube Addiction!

Join TubeSort Today!
...
TubeSort Extension

Take your get rid of youtube challenge to the next level with our free chrome extension.

Get it now!
Browse Categories
Video Description
UPDATE: Get the latest version here https://angularfirebase.com/lessons/google-user-auth-with-firestore-custom-data/

Router Guards are used in Angular to prevent unauthorized users from navigating anywhere they want in your app. At this point our app has a working Firebase authentication system, but any visitor can access routes intended for only logged in users.

Guards handle this problem by implementing the CanActivate interface, which tells Angular whether or not to activate a route. In this example, we will protect pages for unauthenticated users and redirect them to a signin page.

Step 1 - Generate the Guard

We use the CLI in Angular 4 to generate a default guard.

Guards use the injectable decorator, so they need to be registered as a provider just like any other service in the app module.

Step 2 - Update the Auth Service

Our users are authenticating via Firebase and the AngularFire2 package. In the service we are subscribing the FirebaseAuthState, then using a getter to see if the auth object is null. Checkout the OAuth tutorial for more details on this code.

Step 3 - Implement the Guard Logic

Router guards always return a boolean type or boolean observable. The logic here is simple, if the FirebaseAuthState is defined, we activate the route. Otherwise, we return false and navigate to to the login page.

Now that the guard is complete, we just need to apply it to specific routes in the routing module.

That's it for router guards, I'll see you next time.