I am facing an issue with retrieving the title and lastname from a token after decoding it. Despite my efforts, I keep getting an error message that says "cannot read property title of null". If anyone can assist me with this problem, I would greatly appreciate it.
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;
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']);
}
}
}