Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
504 views
in Technique[技术] by (71.8m points)

javascript - How to implement a remember me function?

I am doing an Angular 4 application with node js backend. I did the login form, and all is good I want to implement the function "remember me".

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);
     });
  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...