2
\$\begingroup\$

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.

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

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?

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.