Reputation: 463
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>
<a class="navbar-brand" routerLink="/user-survey/{{Userid}}/{{name}}" *ngIf="this.authService.isAuthenticated()">
<img src="assets/img/waz_home.png" alt="WAZ_logo">
</a>
this is header.ts
ngOnInit() {
debugger;
this.Userid = localStorage.getItem('user_id');
this.name = localStorage.getItem('user.name');
}
I want to get userid as soon as user get logged in.
Upvotes: 1
Views: 799
Reputation: 5833
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'));
console.log(user.name);
You also may want to use a service to shared the data between the header component and the login component.
https://stackblitz.com/edit/angular-qj6kof
https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service
Upvotes: 2
Reputation: 1908
I recommend you have a service that handles logging in and which you can query (instead of localStorage) about the info you need.
BUT
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('user.name');
}
Your header.html doesn't need any changes.
Upvotes: 0