JWT + LocalStorage + Behaviour Subject + Page information dosen´t load refresh the new data

Fisrt Time I log in as USER1 get the token,
home component load the USER1_INFO as espected.
after this i Log out of the app.

Then I Log in USER2
but home.page.ts dosen`t check the USER2 INFO, and render USER1_INFO again

I create a behaviour subject who actually update the information on the service, but no update the componenet controller data.

Login.ts

login(form) {
    this._login.login(form).subscribe({
      next: (res) => {
        localStorage.setItem('user', JSON.stringify(res))
        this._local.$user.next(this._local.getUser())
        let user = this._local.$user.getValue()
        console.log(user);
        this._menuService.menuSubject.next(this._menuService.buildMenu())
        this._router.navigate(['/home/registries'], {replaceUrl: true})
      }, 
      error: (error) => {
        alert('Credenciales incorrectas')
        this._router.navigate(['/login'])
      }, 
      complete: () => {}
    })
  
  }

LocalService.ts

export class LocalService {
  public $user = new BehaviorSubject(this.getUser())
  constructor() { }

  getToken(){
    return JSON.parse(localStorage.getItem('user')) ? 
    JSON.parse(localStorage.getItem('user')).jwt : null
  }
  getUser(){
    return JSON.parse(localStorage.getItem('user'))
  }
  setUser(user:Auth){
    localStorage.setItem('user', JSON.stringify(user))
    this.$user.next(user)
  }
  logOut(){
    localStorage.clear();
   // this.localData.next(this.readUser())   
  }
}

home.ts

 ngOnInit(){
    this._local.$user.next(this._local.getUser())
   this.user = this._local.$user.getValue()
    console.log(this.user);
  }
  ionViewWillEnter(){
    this._local.$user.next(this._local.getUser())
    this.user = this._local.$user.getValue()
     console.log(this.user);
  }
 showLocal(){
    console.log(this.user);
    
  }

runing showlocal from button onclick event, show the correct USER2 object info in log.
but on the component render screen show the USER1 info

Here we have a good explanation of how to make an approximation to the components in a reactive way

Subject service

This completely solves my situation

1 Like