Angular provides the RxJS tool BehaviorSubject for state management tasks where data needs to be distributed between components.
A BehaviorSubject operates as a specialized Subject which contains the most current value that emits it to any subscribing observer.
The RxJS BehaviorSubject saves the latest input value and forwards it to subscribers who join after its creation.
When subscribers join the stream BehaviorSubject will instantly provide them with the latest updated value.
Users of BehaviorSubject receive both their initial value and the most recent value of a stream even when they subscribe after new data has been published. Further, a regular Subject needs subscribers to be present before it can transmit data.
The exchange of user authentication data between components demands the approach of using a BehaviorSubject system. The service can use BehaviorSubject as follows:
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class AuthService {
private authStatus = new BehaviorSubject<boolean>(false);
authStatus$ = this.authStatus.asObservable();
login() {
this.authStatus.next(true); // Update state to logged in
}
logout() {
this.authStatus.next(false); // Update state to logged out
}
}
Login Component
import { Component } from '@angular/core';
import { AuthService } from '../auth.service';
@Component({
selector: 'app-login',
template: `<button (click)="login()">Login</button>`
})
export class LoginComponent {
constructor(private authService: AuthService) {}
login() {
this.authService.login();
}
}
Header Component (Listening to Changes)
import { Component } from '@angular/core';
import { AuthService } from '../auth.service';
@Component({
selector: 'app-header',
template: `<p *ngIf="isLoggedIn">User is logged in</p>`
})
export class HeaderComponent {
isLoggedIn = false;
constructor(private authService: AuthService) {
this.authService.authStatus$.subscribe(status => {
this.isLoggedIn = status;
});
}
}
BehaviorSubject works as an excellent solution for reactive shared data handling in Angular environments.
Ready to transform your business with our technology solutions? Contact Us today to Leverage Our Angular Expertise.