Here I am getting userid from localstorage when user is Authenticated or logged in but that user id is getting as soon as I get logged in even I visit one page to another still not getting but when I reload the page then getting.

What might cause of this issue?

I have logo in header component, in that logo I have given router link and passed parameter as userid, that router only will work when user is logged in, if user is logged out then I have created ng if method that time loggedin logo won't display and won't work. will display other logo.

But when the issue is I need to reload page, without reload page it is not getting

This is header.html code

<a class="navbar-brand" routerLink="" *ngIf="!this.authService.isAuthenticated()">
  <img src="assets/img/logo.png" alt="WAZ_logo">
<a class="navbar-brand" routerLink="/user-survey/{{Userid}}/{{name}}" *ngIf="this.authService.isAuthenticated()">
  <img src="assets/img/waz_home.png" alt="WAZ_logo">

this is header.ts

ngOnInit() {
  this.Userid = localStorage.getItem('user_id'); = localStorage.getItem('');

I want to get userid as soon as user get logged in.

2 Answers

Giovani Vercauteren On Best Solutions

I recommend you have a service that handles logging in and which you can query (instead of localStorage) about the info you need.


You could do it if you refactor your code as follows:

ngOnInit() {
  // empty

get Userid() {
   return localStorage.getItem('user_id');

get name() {
   return localStorage.getItem('');

Your header.html doesn't need any changes.

Jason White On

The localStorage stores strings not objects. You will have to stringify the object and parse it out. Something like this

localStorage.setItem('user', JSON.stringify(user));
let user = JSON.parse(localStorage.getItem('user'));

You also may want to use a service to shared the data between the header component and the login component.