要注销并清除会话存储,你可以使用Angular的LocalStorageService服务和Router服务。以下是一个示例代码,演示了如何在Angular 9中实现注销并清除会话存储:
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { LocalStorageService } from 'ngx-webstorage';
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(
private router: Router,
private localStorageService: LocalStorageService
) { }
// 登录方法
login(username: string, password: string): boolean {
// 在这里实现你的登录逻辑,比如验证用户凭据等
// 模拟登录成功
if (username === 'admin' && password === 'password') {
// 设置会话存储
this.localStorageService.store('isLoggedIn', true);
return true;
}
return false;
}
// 注销方法
logout() {
// 清除会话存储
this.localStorageService.clear('isLoggedIn');
// 导航到登录页面
this.router.navigate(['/login']);
}
// 检查用户是否已经登录
isLoggedIn(): boolean {
// 获取会话存储
return this.localStorageService.retrieve('isLoggedIn') || false;
}
}
import { Component } from '@angular/core';
import { AuthService } from 'auth.service';
@Component({
selector: 'app-navbar',
template: `
`
})
export class NavbarComponent {
constructor(private authService: AuthService) { }
logout() {
// 调用AuthService的logout()方法来注销并清除会话存储
this.authService.logout();
}
}
import { Component } from '@angular/core';
import { AuthService } from 'auth.service';
@Component({
selector: 'app-root',
template: `
`
})
export class AppComponent {
isLoggedIn: boolean;
constructor(private authService: AuthService) { }
ngOnInit() {
// 检查用户是否已经登录
this.isLoggedIn = this.authService.isLoggedIn();
}
}
这样,当用户点击导航栏中的注销按钮时,将调用AuthService的logout()方法来注销并清除会话存储,并导航到登录页面。