Home > Software engineering >  Token from sessionStorage is null in app.component.html
Token from sessionStorage is null in app.component.html

Time:10-12

I'm trying to check if a token exists in the app.component using the following code

app.component.html

<div class="container-scroller">
   <div *ngIf="token">
      <app-navbar></app-navbar>
      <div class="container-fluid page-body-wrapper">
         <app-sidebar></app-sidebar>
         <div class="main-panel">
            <div class="content-wrapper">
               <router-outlet></router-outlet>
            </div>
            <app-footer></app-footer>
         </div>
      </div>
   </div>
   <div *ngIf="token==null">
      <app-login></app-login>
   </div>
</div>

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'star-admin-angular';
  ngOnInit() {
    let token = sessionStorage.getItem('token');
  }
}

The token is not null when i debugged using the ts file. But in the html file the token seems to be null as the login page is always displayed even when there is a token.

CodePudding user response:

Because you didn't declare token as a member of the AppComponent class. It was just a let variable within the ngOnInit(){} scope. You should write:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'star-admin-angular';
  token? : any = undefined;
  ngOnInit() {
    this.token = sessionStorage.getItem('token');
  }
}
  • Related