DEV Community

Chidera Ani
Chidera Ani

Posted on • Originally published at Medium on

Managing auth state in your Angular Firebase app

Managing auth state in your Angular Firebase app.

Firebase authentication usually comes in handy when building any type of application. It helps manage your app’s users, auth state, as well as track user sessions.

In this article we’ll go through tracking authentication state in your angular application and emitting changes to other components using Firebase’s onAuthStateChanged Observable and an RXJS Subject.

let’s dive in……..

In the signin.component.ts , we get login data from the form in our template, which we will then pass to our auth service for authentication.

In our auth.service.ts, we import BehaviourSubject and Observable from RXJS. BehavourSubject is a special type of Observable that allows values to be multicast to many Observers. We also import AngularFireAuth from Angular Fire and auth from Firebase/app.

The following steps explain the process.

Step 1: Initialize a property, currentUser.

Step 2 : Initialize a new BehaviourSubject called authStatusSub and pass currentUser as it’s first value.

Step 3 : Initialize a property, currentAuthStatus which returns authStatusSub as an Obvservable that can be observed across components.

Step 4 : Create a method called authStatusListener and used onAuthStateChanged to check auth state. If a user is Logged in, we call authStatusSub.next and pass in the current user credentials however if no user is logged in, we pass null into authStatusSub.next.

authStatusSub.next passes the current value to all Observers. See https://rxjs-dev.firebaseapp.com/guide/subject for more explanation.

Let’s proceed to listen to it’s emissions in another component.

In header.component.ts, we subscribe to currentAuthStatus from our auth service and pass it’s value into an earlier initialized isAuthenticated property.

In header.component.html, we use conditionals to check if isAuthenticated is truthy or falsy, and then proceed to display elements in accordance.

We’ve been able to successfully track auth state and emit new changes in our auth status across different components. We’ve also been able to subscribe and get emitted values and use in our application logic.

Goodluck coding….

Top comments (0)