Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
512 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...