【发布时间】:2020-01-29 15:40:26
【问题描述】:
我将标题和姓氏存储在令牌中。解码令牌后,我无法获取标题和姓氏以在登录时显示它。它给了我错误“无法读取 null 的属性标题”。 任何人在这里输入代码都可以在这方面帮助我。
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from '../auth.service';
import * as jwt_decode from "jwt-decode";
import { tokenGetter } from '../app.module';
@Component({
selector: 'app-admin-home',
templateUrl: './admin-home.component.html',
styleUrls: ['./admin-home.component.css']
})
export class AdminHomeComponent implements OnInit {
token: any;
title = this.getDecodedAccessToken(this.token).title;
lastname = this.getDecodedAccessToken(this.token).lastname;
// title = 'Herr';
// lastname = 'Fioretto';
constructor(
private router : Router,
private authService: AuthService
) { }
ngOnInit() {
}
//Decoding token
getDecodedAccessToken(token: string): any {
console.log('in decode token function');
try{
let decodedToken = jwt_decode(token);
console.log(decodedToken);
return decodedToken;
}
catch(Error){
return null;
}
}
logout(){
localStorage.removeItem('token');
this.router.navigate(['./login']);
}
isLoggedIn()
{
console.log('in isloggedIn Function')
if(this.authService.isAuthenticated())
{
this.router.navigate(['./admin-home']);
}
else
{
this.router.navigate(['./login']);
}
}
}
【问题讨论】:
-
this.getDecodedAccessToken(this.token)返回null -
好的,我该如何解决这个问题,我需要编写一个单独的函数吗?
-
我也用get title()函数试过了,还是有同样的错误
-
检查您提供给该方法的内容以及它返回的内容 - 如果有任何错误,它会在那里,您应该比我们更了解您的数据和期望。
-
好的,谢谢,我会检查 iit put
标签: angular typescript