Search code examples
rxjsobservableangular8behaviorsubject

loss data when refresh page angular 8


i am losing my role type when refresh the page i made something like if user Admin display dashboard button and user logged in i get the JWT token from server and put it in localstorage and inside the token userID and Role

in my service i used BehaviorSubject as a string and i have function take the token and split it to take the part of body and take the role then Decode it

so if you can help me or something similar to my proplem(i saw like this proplem but all says put the value inside the LocalStorage and i already have put it

AccountServicesService

test$ :BehaviorSubject<string> = new BehaviorSubject('') ;

Login(log: LoginModel): Observable<any> {
   return this.http.post<any>(this.HTTP_URL + 'ApplicationUser/Login' ,
   log, this.headers).pipe(map(x=> {
   this.test$.next(this.roleTypeForCheck(x.token));
   return x;
}));
}

roleTypeForCheck(token): string {
var payLoad = JSON.parse(window.atob(token.split('.')[1]));
var userRole = payLoad.role;
return userRole;
}

LoginComponent

login(){
if(this.loginForm.valid){
  this.validatLoginModel();
  this.service.Login(this.log).subscribe((res:any) => {
    localStorage.setItem('token',res.token);
    this.route.navigate(['home']);
  }, err => {
    if(err.status === 401){
      this.message = 'Email is not confirmed yet!!..Check Your Email';
    } else if(err.status === 400){
      this.message = 'username or password is incorrect';
    } else if(err.status === 500) {
      this.message = 'something wrong..try again later';
    }
    console.log(err);
  });
}
}

NavBarComponent.ts

ngOnInit(): void {
console.log('init');
this.serv.test$.subscribe(res =>{
  this.userRole = res;
  console.log('subscr');
},err =>{
  alert(err.error);
});

NavBarComponent.html

<li class="nav-item">
    <a class="nav-link" routerLink="dashboard" *ngIf="(this.userRole) === 'Admin'">Dashboard</a>
  </li>

Solution

  • I assume you don't want the user to login again after a page refresh. You already stored the token in the localStorage but after the refresh you have to read it from the same place. You could add a method, for example, in your AccountServicesService:

      getTokenFromLocalStorageWithoutLogin() {
        const token = localStorage.getItem('token');
        this.test$.next(this.roleTypeForCheck(token));
      }