我正在为我在angular 10的大学开发一个网站,我有一个tokenstorageservice,它检查用户是否登录,并返回一个令牌和用户的角色。我在我的构造函数中调用我的服务,并在我的ngoninit上设置用户,但是我得到了null。有人能帮我吗?
令牌存储服务
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 } });
}
}
我在控制台上得到的响应令牌为空
1条答案
按热度按时间z9gpfhce1#
在读取令牌服务之前,请尝试检查它是否已初始化。检查以下代码是否有效