0
0
Angularframework~30 mins

BehaviorSubject as simple store in Angular - Mini Project: Build & Apply

Choose your learning style9 modes available
BehaviorSubject as simple store
📖 Scenario: You are building a simple Angular service to hold and share a user's login status across components.
🎯 Goal: Create a simple store using BehaviorSubject to keep track of whether the user is logged in or not.
📋 What You'll Learn
Create a BehaviorSubject to hold a boolean login status
Create a public observable to expose the login status
Add a method to update the login status
Use Angular service with proper imports
💡 Why This Matters
🌍 Real World
Many Angular apps need to share user login status or other state across components. BehaviorSubject is a simple way to build a reactive store for this.
💼 Career
Understanding BehaviorSubject and reactive state management is important for Angular developers working on real-world apps with shared state.
Progress0 / 4 steps
1
Create initial BehaviorSubject
Create an Angular service class called AuthService. Inside it, create a private BehaviorSubject named loggedIn initialized with false. Import BehaviorSubject from rxjs.
Angular
Need a hint?

Use new BehaviorSubject<boolean>(false) to create the initial store.

2
Add public observable for login status
Add a public readonly observable called isLoggedIn$ that exposes the loggedIn BehaviorSubject as an observable using the asObservable() method.
Angular
Need a hint?

Use this.loggedIn.asObservable() to expose the BehaviorSubject as observable.

3
Add method to update login status
Add a public method called setLoginStatus that takes a boolean parameter status and calls next(status) on the loggedIn BehaviorSubject to update the login status.
Angular
Need a hint?

Define setLoginStatus(status: boolean) and call this.loggedIn.next(status) inside it.

4
Complete the Angular service
Ensure the AuthService class is decorated with @Injectable({ providedIn: 'root' }) and all imports are present. The service should now act as a simple store for login status using BehaviorSubject.
Angular
Need a hint?

Check that @Injectable and imports are correctly added at the top.