Angular 4, remember me function

2019-06-28 02:06发布

问题:

I am doing an angualar 4 application with node js backend. I did the login form and all is good i want to implement the function remember me. Thank you in advance. This my login service:

import { Injectable } from '@angular/core';

@Injectable()
export class loginService{
  rememberMe: boolean;
  constructor() { }

login(credentials) {
  sessionStorage.setItem('Name', credentials.firstName);
  sessionStorage.setItem('token', credentials.token);
}

getCostumer() {
  const user = {
    Name:  sessionStorage.getItem('firstName'),
    token: sessionStorage.getItem('token')
}

This is the component:

constructor(private signInService: SignInService, private router: Router, 
public dialog: MatDialog, private authService: AuthService) { }

ngOnInit() { }

  login(costumer) {
     this.loginService.login(costumer).subscribe((data) => {
       this.authService.login(data);
       this.router.navigate(['home']);
       this.dialog.closeAll();
      }, err => {
       this.message = err._body;
       console.log(this.message);
     });
  }
}

回答1:

Use localStorage instead of sessionStorage

In your case, you can do something like this:

if (isRemberMeChecked) {
    ...
    localStorage.setItem('Name', credentials.firstName);
    localStorage.setItem('token', credentials.token);
    ...
} else {
    ...
    sessionStorage.setItem('Name', credentials.firstName);
    sessionStorage.setItem('token', credentials.token);
    ...
}

If you want to get isRemberMeChecked value globally you can use angular service



回答2:

What you want to do here is use localStorage for the rememberMe and credentials.firstName. The credentials.token you can store in the sessionStorage:

login(credentials) {
  localStorage.removeItem('Name');
  localStorage.removeItem('RememberMe');
  sessionStorage.setItem('token', credentials.token);
  if(rememberMe){
    localStorage.setItem('Name', credentials.firstName);
    localStorage.setItem('RememberMe', JSON.stringify(this.rememberMe));
  }
}

After a reload it will fetch the RememberMe and Name:

if(JSON.parse(localStorage.getItem('RememberMe')) !== null)
{
  this.name = localStorage.getItem('Name');
  this.rememberMe = JSON.parse(localStorage.getItem('RememberMe'));
}