angular6中进行登录的用户信息进行缓存localStorage本地存储

想要在Angular6项目中进行登陆的账户信息缓存,我们需要在登录组件中把用户信息保存到本地通过localStorage,然后直接在另外一个组件中进行调用即可,代码如下:

login.component.ts

 this.userID = this.loginData.data.userId;
 this.loginplay = this.loginData.data.userName;
 window.localStorage["userId"] = this.userID;
 window.localStorage["userName"] = this.loginplay;

需要调取账户信息的组件直接调用:

  this.titleAlldata = localStorage["userName"];
  this.userId = localStorage["userId"];

在登出账号的时候我们要对用户的缓存信息进行清除处理,即消除本地缓存缓存localStorage

saveBtn1(){
    this.http.post(this.api+'/v1/logout',{},{withCredentials: true}).subscribe(data=>{
      this.ErrorData = data;
      if(this.ErrorData.code == 10000){
        window.localStorage.removeItem("userName");
        window.localStorage.removeItem("userId");
        this.router.navigate(['login']);
      }else if(this.ErrorData.code == 10005){
        this.router.navigate(['login']);
      }else{
        this.alertTitle = this.ErrorData.message;
        $('.zmalert1').fadeIn();
      }      
    },error =>{
      $('.ErrorAlert1').fadeIn().delay(1500).fadeOut();
    })
  }

这样就可以吧账户信息在登陆的时候存到本地缓存,然后登出的时候进行消除缓存。

你可能感兴趣的:(angular4-6开发)