how to retain the localstorage session when refreshing page using typescript

Viewed 48
  isLogin = false;
  isLogged = new Subject<boolean>();

  constructor(private _httlpClient: HttpClient) {}

  login(credential: any): any {
    this.isLogin = false;
    if (credential != '') {
      this.isLogin = true;
    }
    this.isLogged.next(this.isLogin);
    return this._httlpClient.post(this.url, credential);
  }


  <!--This is the function where i need to retain data-->
  setSession(token: string) {
    localStorage.setItem('authToken', token);
  }

  getSession() {
    return localStorage.getItem('authToken');
  }
}

after i logged in the profile page should be remained displayed until i logout, but when i refresh the page the profile page is already missing.

1 Answers

In ngOnInit(), check the session status and update the BehaviorSubject accordingly.

import { HttpClient } from '@angular/common/http';
    import { Component, OnInit, VERSION } from '@angular/core';
    import { BehaviorSubject, Subject } from 'rxjs';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css'],
    })
    export class AppComponent implements OnInit {
    
      isLogin = false;
      isLogged = new BehaviorSubject<boolean>(false);
    
      constructor(private _httlpClient: HttpClient) {}
    
      ngOnInit() {
        if (this.getSession() !== null) {
          this.isLogin = true;
        }
        this.isLogged.next(this.isLogin);
      }
    
      login(credential: any): any {
        this.isLogin = false;
        if (credential != '') {
          this.isLogin = true;
        }
        this.isLogged.next(this.isLogin);
        return this._httlpClient.post(this.url, credential);
      }
    
      // This is the function where i need to retain data
      setSession(token: string) {
        localStorage.setItem('authToken', token);
      }
    
      getSession() {
        return localStorage.getItem('authToken');
      }
    }

code snippet

Related