# Rewrite BehaviorSuject that takes either localStorage or Observable in Angular

I have this code

employee = this.identityService.me;
employeeToken: Observable<string> = this.employee.pipe(map((e) => e.token));

currentHead = new BehaviorSubject(localStorage.getItem('head'));


What I need to do is to change the currentHead if the local storage is empty. So I do this in the ngOnInit

ngOnInit() {
this.employeeToken.subscribe(e => {
if (!this.currentHead.value || this.currentHead.value === '') {
this.currentHead.next(e);
}
});
}


It works, but somehow I feel like this should e feasible with rxjs in the initialization of currentHead, no?

Where I failed is, that the local storage is not an observable but this.employee is, so I struggle to compare them. I tried some convert observable to behaviorsubject but that didn't work either.

## 1 Answer

I think the ngOnInit() is the best suitable way for that. Clean and easy to spot. The initialization of the other two variables should also be part of ngOnInit (employee and employeeToken).

Something like that:

employee: Empoyee;
employeeToken: Observable<string>;
currentHead: BehaviorSubject<ADD-TYPE-HERE>;

...

ngOnInit() {
const headFromStorage = localStorage.getItem('head');
employee = this.identityService.me;
employeeToken = this.employee.pipe(map((e) => e.token));
this.currentHead = new BehaviorSubject(localStorage.getItem('head'));

this.employeeToken.subscribe(e => this.currentHead.next(e));
}



Not sure you need this:

if (!this.currentHead.value || this.currentHead.value === '') {


Because this is a subscription. Every time the empoloyeeToken change, you have to update it, right?