如果用户已登录,我需要显示用户名。我已经将用户名和令牌都存储到了本地存储中。
如何在可以显示在html上的navbar的ngOnInit上获取此用户。
这是我的密码。
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();
}
}
{{1}}
答案 0 :(得分:0)
在AuthService中
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
}
}