【问题标题】:TypeError: Cannot read property 'title' of null TypeError: Cannot read property 'title' of nullTypeError:无法读取 null 的属性“标题” TypeError:无法读取 null 的属性“标题”
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • 找不到名称“标题”。你的意思是实例成员'this.title'。同样对于姓氏,是的,这也在改变风格
  • 我已经更新了代码(this.title 和 this.lastname)
  • 它破坏了整个页面的布局
  • 为什么不简单地设置值并从 localStorage 中获取呢?像 localStorage.set('title', title);或 localStorage.set('lastname', lastname);然后在任何地方获取它 localStorage.getItem('title');
  • title = this.userService.getDecodedAccessToken(localStorage.getItem('token')).title; lastname = this.userService.getDecodedAccessToken(localStorage.getItem('token')).lastname WOKRED::::
【解决方案2】:

最好在 ngOnInit 中调用方法。

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

【讨论】:

  • DIDNT WORKED 它改变了页面的整体风格
猜你喜欢
  • 2018-09-12
  • 2022-06-19
  • 1970-01-01
  • 2021-02-27
  • 2017-10-27
  • 1970-01-01
  • 2021-08-04
  • 2022-01-12
  • 2021-12-04
相关资源
最近更新 更多