In this article, I will show you how to manage user authentication status with the help of the BehaviorSubject.

Why BehaviorSubject?

The BehaviorSubject represents a value that changes over time, like the user authentication status for example. But the real power of the BehaviorSubject, in this case, is that every subscriber will always get the initial or the last value that the subject emits.

From the docs:

Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications.

Let’s start coding, and I hope you will understand better the concept and why we need the BehaviorSubject in this case.

First, let’s create the AuthService:

We are creating new BehaviorSubject and setting the initial value to be the results from our hasToken function.

The hasToken function is only checking if the user has a token in his local storage and returns the results as a boolean.

We are saving the token to local storage and sending the next status to our subscribers. ( In real life this will be after HTTP call )

We are removing the token from local storage and sending the next status to our subscribers.

A subject in Rx is both Observable and Observer. In this case, we only care about the Observable part, letting other parts of our app the ability to subscribe to our Observable.

We can return only the Observable part of our subject with the help of the asObservable function.

Now we can use the AuthService, and because we are working with Observables, we can use the async pipe.

Now imagine you have a component that listens to the isLoggedIn Observable after we already call the next method, with simple Observable or Subject the component will not get any data.

That’s why we need the BehaviorSubject because now it does not matter when you register the subscriber, he will get the last or initial value, and that’s what we want.

The complete AuthService:

last note:

You should consider using the share operator in this case because we want to avoid from creating multiple subscriptions. (see @Mark Pieszak comment)

That’s all!

You can join to my Angular group on Linkedin to get the latest resources about Angular.

☞ Please tap or click “︎❤” to help to promote this piece to others.