Angular 4,记住我的功能

时间:2018-03-27 09:21:25

标签: javascript angular typescript local-storage angular2-template

我正在使用节点js后端进行angualar 4应用程序。我做了登录表单,一切都很好,我想实现功能记得我。 先感谢您。 这是我的登录服务:

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

这是组件:

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 个答案:

答案 0 :(得分:5)

使用localStorage代替sessionStorage

在您的情况下,您可以执行以下操作:

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

如果您想全局获取isRemberMeChecked值,可以使用角度服务

答案 1 :(得分:1)

您要在此处使用 localStorage 作为 rememberMe credentials.firstName 。您可以在 sessionStorage 中存储的 credentials.token

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

重新加载后,它会获取 RememberMe 名称

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