Error: Unable to access to the 'title' property of a null value

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']);
      }

  }


}

Answer №1

One solution is to set the 'title' and 'lastname' variables as empty strings without affecting the style:

title: string = '';
lastname: string = '';
ngOnInit() {
  this.title = this.getDecodedAccessToken(this.token).title;
  this.lastname = this.getDecodedAccessToken(this.token).lastname;
}

Answer №2

It's recommended to invoke your functions within the ngOnInit lifecycle hook.

title: string;
lastname: string;

ngOnInit() {
  title = this.retrieveDecodedToken(this.token).title;
  lastname = this.retrieveDecodedToken(this.token).lastname;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Pattern for path configuration in tsconfig.json

Is there a way to dynamically include files based on path patterns? Currently, my scripts contain lines like this: import '../../../../myresource/src/shared/my-interface' However, I'm interested in simplifying it to something like: import ...

Encountering a TypeScript error in MUI 5 when attempting to spread values in props

I am encountering an issue with a typescript error related to the MUI sx prop. The problem arises when I attempt to merge or spread multiple sx values into an sx prop, resulting in an error. It seems to work fine if only one item is present in the sx prop, ...

Tips for updating the font size of your MUI Accordion title

I was attempting to adjust the font size of the MUI-5 Accordion title. It seems like I need to override it, but I am unsure about how to do so with CSS in MUI-5. Instead of 'SX', it uses 'htmlSx'. When I tried using it, it did not produ ...

WebStorm is maxing out the CPU at full capacity

Currently using WebStorm 11 for development in Angular2, I've noticed a significant increase in CPU usage when the IDE is open. While the ng serve command runs smoothly in the background with minimal impact on performance, opening WebStorm causes CPU ...

Transforming Javascript into Typescript with node modules in Visual Studio 2015

After developing a JavaScript web app using npm and webpack, I successfully converted all the .js files to .ts using the PowerShell command found here. Now, I am looking to transition to a VS2015 TypeScript project but struggling to find guidance on how ...

Using the equal sign in an Angular variable: a simple guide

I have a task that requires me to do the following: <app-tooltip #tooltip1 content="{{'content'='errorName1' | translate}}" ></app-tooltip> <app-tooltip #tooltip2 content="{{'content'='errorName2' | t ...

Is it possible to use Meteor with the latest version of Angular 2?

I'm currently using Meteor 1.4.1 with rc4 and wondering if there's a way to integrate the final version of Angular 2 with it. Should I wait for an updated version from Meteor, or is there a way to use it now? ...

When using Ionic 3 on an Android device, the keyboard is causing the tabs and app content to shift upwards

I'm currently working on an Ionic 3 app and encountering a problem. Whenever I click on the search function, the keyboard opens and pushes all the content of the app to the top. https://i.sstatic.net/GaPW8.png https://i.sstatic.net/7d6Fm.png Here i ...

Guide to defining custom variables from various locations within Angular Js

In my Angular 6 project, I have noticed that in the home.component.ts file, there is a variable being declared at the beginning: public hasResults = false; Then in the home.component.html file, there is a section for displaying this variable: <span st ...

Encountering the identical error message while attempting to execute my application: "Uncaught TypeError: this.microservicesModule.register is not a function."

Despite my repeated attempts to run the application, I am consistently encountering the following error message: "UnhandledPromiseRejectionWarning: TypeError: this.microservicesModule.register is not a function at NestApplication.registerModules ...

Are there any tools or terminal commands available to identify all deprecated methods being used in a project?

When coding in VS Code, deprecated methods are easily identified with a helpful strikethrough when working on individual files. Is there a method to search an entire project (specifically Angular) to locate and flag all instances of deprecated methods wi ...

Best practice in Angular 2: The difference between binding an object as a whole versus binding its individual

What is the best approach for a child component when dealing with object properties and change events? Example 1 <parent-component> <child-component [exampleInput]="object.val" (valueChanged)="updateObjectValue($event)"> ...

Tips for creating a carousel with Angular 9 to showcase numerous items

I've got this code snippet that I'm working on. I want to incorporate a Carousel feature using Angular 9 without relying on any external libraries. Currently, all the data items are appearing in a single row (they are exceeding the specified bor ...

TS2403 Error: Variable 'crypto' must be of type 'Crypto' as subsequent variable declarations must have the same type - currently has type 'Crypto'

Since today, we have encountered problems deploying our project. In the drone logs during the build step, the following error is appearing: Error: node_modules/@types/node/ts4.8/crypto.d.ts:4477:13 - error TS2403: Subsequent variable declarations must hav ...

Exploring the Latest Features: Using Angular 7 with Bootstrap Collapse for Dynamic Aria-Controls

I am currently working on creating my own component to use within an *ngFor loop. I am facing an issue where I need a unique value for my Collapse feature. Right now, when I click on the second main row in the table, the collapse feature only shows the inn ...

Issue with Angular 2: Unable to connect to 'model' as it is not recognized as a valid property of 'p-steps'

I've been struggling to run the code below: states.component.html <p-steps [model]="items"></p-steps> import { Component, OnInit } from '@angular/core'; import { StepsModule, MenuItem } from 'primeng/primeng'; impo ...

Typescript - Loading Data into a Dropdown Menu

I'm facing an issue with my app where I have a component called week-selector. It's a simple dropdown with team names, but I'm encountering an error related to the @Output() function. The error message says: Generic Type 'EventEmitte ...

Update Table on Adding New Item

Just starting out here. I've been working with ngx-datatable. Is there a method to refresh the UI view of the ngx-datatable? Like completely re-render everything Please take a look at the screenshots: https://i.sstatic.net/EdB9p.png https://i.sst ...

Exploring how to utilize checkboxes in Angular Material for data filtering from a database. Encountering an issue with the error message "nameValue

When attempting to utilize checkboxes to filter data in a material table, I ensured there were no errors present on my terminal or console. However, upon checking a checkbox in the browser, an error message stating "nameValue.toLowerCase is not a function" ...

Using Typescript to assign a custom object to any object is a powerful feature

I am attempting to organize table data by utilizing the code found at https://github.com/chuvikovd/multi-column-sort. However, I am unsure of how to pass a custom object to the SortArray[T] object. The structure of my custom object is as follows: const ob ...