I have angular application which has header, user section, timeline components. In header, I have log in form. After log in user redirected to timeline component which calls user section component. In header component I need to store user data in localstorage after log in. And that data I need to access in user section.
Header component: on successfull login getUserDetails()
is called
getUserDetails() {
this.userService.getUserDetails(this.id).subscribe((data) => {
if (data["status"] === false) {
} else {
this.loadingFlag = true;
this.selecteduser = data["data"];
localStorage.setItem(
"selecteduser",
JSON.stringify(data["data"])
);
}
});
}
user-section component
ngOnInit(): void {
console.log('user sec', JSON.parse(localStorage.getItem('selecteduser'))); // Gives null after
//log in
}
I tried to get data using BehaviorSubject
also in multiple ways but didn't worked e.g. like here. It shows null every time. Its like getting value as soon as it is set as after log in redirected to component which tries to get set data.
How can I get localstorage data in user-section component which is set in header component?
I tried to explain but sorry if I confuse while explaining my problem.
Please guide and help. Thanks.
Edit:
In user section I need to access that localstorage data on condition.
ngOnInit(): void {
this.getUserDetails();
}
getUserDetails() {
if (this.user_id == null) {
console.log('user sec',
JSON.parse(localStorage.getItem('selecteduser')));
this.selecteduser = JSON.parse(localStorage.getItem('selecteduser'));
this.fullName =
this.selecteduser.first_name + ' ' + this.selecteduser.last_name;
this.userVerified = this.selecteduser.verified;
}
else if(this.user_id == this.id)
{
this.selecteduser = JSON.parse(localStorage.getItem('selecteduser'));
this.fullName =
this.selecteduser.first_name + ' ' + this.selecteduser.last_name;
this.userVerified = this.selecteduser.verified;
}
else{
// other api call
}
}
Edit 2: First login
Then logout and login 2nd time
Then logout and login 3nd time