Angular6 如何在ngOnInit获得localstorage的价值

Angular6 如何在ngOnInit获得localstorage的价值,angular6,Angular6,如果用户登录,我需要显示用户名。我已将用户名和令牌存储到localstorage 如何在导航栏的ngOnInit中获取该用户的信息,我可以在html中显示该信息 这是我的密码 导航条组件 认证服务 导出类身份验证服务{ private loggedIn=new BehaviorSubject(this._tokenService.loggedIn()); //更改日志,然后更改身份验证状态 authStatus=this.loggedIn.asObservable(); changeAuthSt

如果用户登录,我需要显示用户名。我已将用户名和令牌存储到localstorage

如何在导航栏的ngOnInit中获取该用户的信息,我可以在html中显示该信息

这是我的密码

导航条组件 认证服务
导出类身份验证服务{
private loggedIn=new BehaviorSubject(this._tokenService.loggedIn());
//更改日志,然后更改身份验证状态
authStatus=this.loggedIn.asObservable();
changeAuthStatus(值:布尔值){
this.loggedIn.next(值);
}
构造函数(专用令牌服务:令牌服务){
if(this._tokenService.loggedIn()==true)
这是。_tokenService.getUser();
}
}

@nas尝试一下

在这里,我们将首次将数据存储在
本地存储中
,如果数据已经存在,我们将使用它

在AuthService中

导航栏组件中的

export class NavbarComponent implements OnInit {

    public loggedIn: boolean;
    public user: any;

    constructor(private _authService: AuthService, private _router: Router) { }

    ngOnInit() {
        this._authService.authStatus
            .subscribe(
                value => {
                    this.loggedIn = value

                }
            );
    }
export class AuthService {

    private loggedIn = new BehaviorSubject<boolean>(this._tokenService.loggedIn());
    //loggedIn change then change authstatus
    authStatus = this.loggedIn.asObservable();

    changeAuthStatus(value: boolean) {
        this.loggedIn.next(value);
    }

    constructor(private _tokenService: TokenService) {
        if (this._tokenService.loggedIn() == true)
            this._tokenService.getUser();
    }
}
constructor(private _tokenService: TokenService) {
        if (this._tokenService.loggedIn() == true)
            this._tokenService.getUser();
         else{
             localStorage.setItem('Authentication',(set your Authentication token Value)); //headers.get('Authorization')
             localStorage.setItem('login',(set your login boolean Value));
           );
         } 
    }
export class NavbarComponent implements OnInit {

    public loggedIn: boolean;
    public user: any;

    constructor(private _authService: AuthService, private _router: Router) { }

    ngOnInit() {
     this.loggedIn = sessionStorage.getItem('login');
     //use this loggedIn variable to check whther user login status 
      }
  }