我正在用Angular 10为我的大学开发一个网站,我有一个TokenStorageService,用于检查用户是否为loggedIn并返回令牌和用户的角色。我在构造函数中调用服务并在ngOnInit上设置用户但我得到的是null。有人能帮我吗?
- TokenStorageService
import { Injectable } from '@angular/core';
const TOKEN_KEY = 'auth-token';
const USER_KEY = 'auth-user';
@Injectable({
providedIn: 'root'
})
export class TokenStorageService {
constructor() { }
signOut() {
window.sessionStorage.clear();
}
logout() {
window.sessionStorage.removeItem(TOKEN_KEY);
window.sessionStorage.removeItem(USER_KEY);
}
public saveToken(token: string) {
window.sessionStorage.removeItem(TOKEN_KEY);
window.sessionStorage.setItem(TOKEN_KEY, token);
}
public getToken(): string {
return sessionStorage.getItem(TOKEN_KEY);
}
public saveUser(user) {
window.sessionStorage.removeItem(USER_KEY);
window.sessionStorage.setItem(USER_KEY, JSON.stringify(user));
}
public getUser() {
console.log(JSON.parse(sessionStorage.getItem(USER_KEY)));
return JSON.parse(sessionStorage.getItem(USER_KEY));
}
}
- 我调用的组件
export class AutorizarCriacaoContaComponent implements OnInit {
currentUser: any;
tipoUsuario: number;
authToken: string;
tipo: string;
// usuario solicitante
u = {} as Usuario;
constructor(private token: TokenStorageService, private router: Router, private actRoute: ActivatedRoute,
private accountService: AccountService, private spinner: NgxSpinnerService) {
this.authToken = this.actRoute.snapshot.params.authToken;
// this.currentUser = this.token.getUser();
}
ngOnInit() {
// console.log(this.token.getToken());
this.currentUser = this.token.getUser();
this.getRoles();
this.getUsuarioBytoken();
}
getRoles() {
for (let role of this.currentUser.roles) {
// tslint:disable: triple-equals
// console.log(this.currentUser.roles.includes('ROLE_ALUNO'));
if (role.authority == 'ROLE_ALUNO') {
this.tipoUsuario = 1;
}
if (role.authority == 'ROLE_ADMIN') {
this.tipoUsuario = 2;
}
if (role.authority === 'ROLE_USER' || role.authority === 'ROLE_PROFESSOR') {
this.tipoUsuario = 3;
}
}
return this.tipoUsuario;
}
getUsuarioBytoken() {
// tslint:disable: deprecation
this.accountService.getUsuarioByToken(this.authToken).subscribe((v: VerificationToken) => {
this.u = v.usuario;
if (this.u.roles[0].type === 'ROLE_ALUNO') {
this.tipo = 'aluno';
}
if (this.u.roles[0].type === 'ROLE_USER' || this.u.roles[0].type === 'ROLE_PROFESSOR') {
this.tipo = 'professor';
}
});
}
autorizarConta() {
this.spinner.show();
// tslint:disable-next-line: deprecation
this.accountService.autorizarConta(this.authToken).subscribe(response => {
const res = response;
if (res.result === 'conta.autorizada') {
this.spinner.hide();
Swal.fire(
'Tudo certo!',
'Conta autorizada!',
'success'
);
setTimeout(() => {
this.router.navigate(['/home2']);
}, 4000);
}
});
}
redirect() {
this.router.navigate(['/login'], { queryParams: { redirectUrl: '/conta/autorizar/' + this.authToken } });
}
}
- 我得到的响应令牌在我的控制台上为空
在读取令牌服务之前,尝试检查它是否已初始化。检查以下代码是否有效
ngOnInit() {
this.currentUser = this.getCurrentUser();
this.getRoles();
this.getUsuarioBytoken();
}
getCurrentUser(): any {
if (this.token.getUser()) {
return this.token.getUser();
} else {
setTimeout(() => getCurrentUser(), 10);
}
}