TypeError:无法读取null的属性“ title” TypeError:无法读取null的属性“ title”

时间:2019-09-30 10:44:12

标签: angular typescript

我将标题和姓氏存储在令牌中。解码令牌后,我无法获得标题和姓氏以在登录时显示它。它给我的错误是“无法读取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']);
      }

  }


}

2 个答案:

答案 0 :(得分:0)

最好在ngOnInit内部调用方法。

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

答案 1 :(得分:0)

您应该尝试将其设为空字符串,这不会改变样式

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