Wasif Zaman
Wasif Zaman

Reputation: 33

how to use sessionStorage instead of localStorage in angular 7?

I am new to angular and asp.net web api. I am creating website using asp.net web api and angular 7 and i done registration and login work but now i need to use sessionStorage instead of localStorage in angular code. i am sharing all that files where i use localStorage and localStorage code is working perfectly but now i need to use sessionStorage .it show all the information of user which is login currently .kindly help me. thank you.i share all the code that i have done for localstorage i know it confusing but hope you can solve my problem.i remove import statements from code and html code which done to show login user info like username email and full name.

This is the interceptor class

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

    constructor(private router: Router) {

    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        if (localStorage.getItem('token') != null) {
            const clonedReq = req.clone({
                headers: req.headers.set('Authorization', 'Bearer ' + localStorage.getItem('token'))
            });
            return next.handle(clonedReq).pipe(
                tap(
                    succ => { },
                    err => {
                        if (err.status == 401){
                            localStorage.removeItem('token');
                            this.router.navigateByUrl('/user/login');
                        }
                    }))}
        else
            return next.handle(req.clone());
    }}


  //login compnent ts file 
    @Component({
      selector: 'app-login',
      templateUrl: './login.component.html',
      styles: []
    })
    export class LoginComponent implements OnInit {

      formModel ={
        UserName :'',
        Password:''
      }
      constructor(private service: UserService, private router: Router, private toastr: ToastrService) { }

      ngOnInit() {
    if (localStorage.getItem('token') != null)
      this.router.navigateByUrl('/home');
  }
  onSubmit(form: NgForm) {
    this.service.login(form.value).subscribe(
      (res: any) => {
        localStorage.setItem('token', res.token);
        this.router.navigateByUrl('/home');
      },
      err => {
        if (err.status == 400)
          this.toastr.error('Incorrect username or password.', 'Authentication failed.');
        else
          console.log(err);
      }
    );
  }

}

//auth.grud.ts file

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {

  constructor(private router: Router) {

  }
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): boolean {
    if (localStorage.getItem('token') != null)
      return true;
    else {
      this.router.navigate(['/user/login']);
      return false;
    }

  }
}

//home component.ts file

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styles: []
})
export class HomeComponent implements OnInit {
  userDetails;

  constructor(private router: Router, private service: UserService) { }

  ngOnInit() {
    this.service.getUserProfile().subscribe(
      res => {
        this.userDetails = res;
      },
      err => {
        console.log(err);
      },
    );
  }

  onLogout() {
    localStorage.removeItem('token');
    this.router.navigate(['/user/login']);
  }
}

kindly tell me how can i do this task.

Upvotes: 1

Views: 530

Answers (1)

cssyphus
cssyphus

Reputation: 40096

This is more of a JavaScript question than an Angular question... (javascript tag added to question)

LocalStorage and SessionStorage are used identically.

If you look in DevTools (F12), on the Application tab (under "Storage"), you will see both LocalStorage and SessionStorage.

You can use either one, or both. And they both work the same:

localStorage.setItem('myVarName', 'String to store');

sessionStorage.setItem('myVarName', 'String to store');

and

const stord = localStorage.getItem('myVarName');

const stord = sessionStorage.getItem('myVarName');

The difference between them, of course, is that the SessionStorage variables disappear the moment the browser tab is closed, whereas the LocalStorage variables persist until they are deleted (either via code localStorage.removeItem('myVarName') or by clearing cookies / history.

See Also:

When is localStorage cleared?

Upvotes: 0

Related Questions