Angular 4, remember me function

2019-06-28 01:57发布

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);
     });
  }
}

2条回答
时光不老,我们不散
2楼-- · 2019-06-28 02:04

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'));
}
查看更多
一纸荒年 Trace。
3楼-- · 2019-06-28 02:25

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

查看更多
登录 后发表回答