Home > database >  Getting the value of local storage with Observable is not working in Angular
Getting the value of local storage with Observable is not working in Angular

Time:10-27

Hi I am trying to get the value from local storage by using observable but it is not working.

My code is:

of(JSON.parse(localStorage.getItem('isManager'))).pipe(
      takeWhile(() => this.alive),
      map((isManager: boolean) => {
        console.log('isManager', isManager);
        this.doNavigation(isManager);
      })
    );

The problem is that it is not going inside the map body and there is a value present in local stroage regarding this field.

CodePudding user response:

Why not use

const isManager = localStorage.getItem('isManager') === 'true';
// You need to convert the string stored in local storage to a boolean.

if (isManager) {
  this.doNavigation(isManager);
}

What is the point of using of to create an observable that is mapped to undefined? Very smelly code.

CodePudding user response:

It can be done as follow:

of(JSON.parse(localStorage.getItem('isManager'))).pipe(
      takeWhile(() => this.alive),
      map((isManager: boolean) => {
        console.log('isManager', isManager);
        this.doNavigation(isManager);
      })
    ).subscribe();
  • Related