通过sessionStorage与token维护用户登录状态
login/login.component.html
<input type="text" [value]="userForm.username">
<input type="text" [value]="userForm.password">
<button (click)="login()">login</button>
login/login.component.ts
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from 'src/app/services/auth.service';
import { SettingService } from 'src/app/services/setting.service';
@Component({
selector: 'uv-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.less']
})
export class LoginComponent implements OnInit {
userForm: any = {
username: 123,
password: 456,
name: 'name'
}
constructor(
private authService: AuthService,
private router: Router,
private settingService: SettingService
) { }
ngOnInit(): void {
}
login() {
console.log("login begin")
console.log(this.authService.isLogin)
this.authService.loginTest(this.userForm).subscribe(() => {
if (this.authService.isLogin) {
this.router.navigate(['/test1'])
}
}, () => {
console.log("--------")
})
}
}
src\app\services\auth.service.ts
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { SettingService } from './setting.service';
import { tap } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class AuthService {
// 存储的KEY
key = 'Auth';
// 是否登录
isLogin = false
// 用户信息
private _user!: User
get user(): User {
if (!this._user) {
let session = this.settingService.getSession(this.key);
let local = this.settingService.getLocal(this.key);
this._user = Object.assign(new User(), session ? session : local);
this.settingService.setSession(this.key, this._user);
}
return this._user;
}
set user(value: User) {
this._user = Object.assign(this._user ? this._user : new User(), value);
this.settingService.setSession(this.key, this._user);
}
removeLocal() {
this.settingService.removeLocal(this.key);
console.log(this.settingService.getLocal(this.key))
}
removeSession() {
this.settingService.removeSession(this.key);
}
constructor(private settingService: SettingService) {
if (this.user.username && this.user.token) {
this.isLogin = true;
}
}
loginTest(user: User): Observable<any> {
return new Observable((x) => {
let test = {
name: 'admin',
token: 'token'
}
this.user = Object.assign(user, test)
this.isLogin = true
x.next(this.user)
x.complete()
})
}
/**
* 登录
* @param {User} user
* @returns {Observable<result<string>>}
* @memberof AuthService
*/
login(user: User): Observable<any> {
return new Observable((x) => {
this.httpService.post(`/login`, user).subscribe(
(z) => {
this.user = Object.assign(user, z);
this.isLogin = true;
x.next(z);
x.complete();
},
(k) => {
x.error(k);
x.complete();
},
() => {
x.complete();
}
);
});
}
/**
* 登出
*
* @returns {Observable<boolean>}
* @memberof AuthService
*/
logout(): Observable<boolean> {
return of(true).pipe(
tap(() => {
console.log("tap...")
this.removeLocal();
this.removeSession();
this.isLogin = false;
})
);
}
}
/**
* 用户对象
*
* @export
* @class User
*/
export class User {
// 用户名
username?: string = '';
// 密码
password?: string = '';
// token
token?: string = '';
// 名称
name?: string = ''
}
src\app\services\setting.service.ts
import { Injectable } from '@angular/core';
/**
* 设置服务
*
* @export
* @class SettingsService
*/
@Injectable({ providedIn: 'root' })
export class SettingService {
constructor() { }
/**
* 获取本地值
*
* @param {string} key 关键字
* @returns
* @memberof SettingsService
*/
getLocal(key: string) {
return JSON.parse(localStorage.getItem(key) || 'null') || null;
}
/**
* 设置本地值
*
* @param {string} key 关键字
* @param {*} value 值
* @memberof SettingsService
*/
setLocal(key: string, value: any) {
localStorage.setItem(key, JSON.stringify(value));
}
/**
* 获取当前会话的值
*
* @param {string} key 关键字
* @returns
* @memberof SettingsService
*/
getSession(key: string) {
return JSON.parse(sessionStorage.getItem(key) || 'null') || null;
}
/**
* 设置当前会话值
*
* @param {string} key 关键字
* @param {*} value 值
* @memberof SettingsService
*/
setSession(key: string, value: any) {
sessionStorage.setItem(key, JSON.stringify(value));
}
/**
* 移除本地值
*
* @param {string} key 关键字
* @memberof SettingsService
*/
removeLocal(key: string) {
localStorage.removeItem(key);
}
/**
* 移除当前会话
*
* @param {string} key 关键字
* @memberof SettingsService
*/
removeSession(key: string) {
sessionStorage.removeItem(key);
}
}