Reputation: 847
in my Dasboard Component
i Need to Give a username
and Send it
Form Server for Get Detail of User like fName , lName , Image , . . .
I Pass the username
with this way :
when user is loggedin i u get the username
from LocalStorage
:
Login Component :
private usenameSource = new BehaviorSubject<string>('');
userName$ = this.usenameSource.asObservable();
getDecodedAccessToken(): any {
return jwt_decode(this.getRawAuthToken(AuthTokenType.AccessToken));
}
getUserNameDecode():any {
const decode = this.getDecodedAccessToken();
let userName = decode["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"];
return this.usenameSource.next(userName);
}
Dashboard Component :
this.loginService.userName$.subscribe((data) => {
this.userName = data;
})
Now, the problem is that when the browser is refreshing, the username will be null and I need to login again.
whats the problem ? how can i solve this problem ?
Upvotes: 0
Views: 138
Reputation: 66
When the page refreshes, the "usenameSource" value will be cleared. To keep it, call your method "getUserNameDecode()" again in your service constructor.
constructor(...) {
this.getUserNameDecode();
}
getUserNameDecode():any {
const decode = this.getDecodedAccessToken();
if(!decode) {
// login failed
return;
}
let userName = decode["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"];
return this.usenameSource.next(userName);
}
....
Upvotes: 2
Reputation: 1229
I assume that Login Component will be loaded first when you start your application.
And also I assume that you are storing the userName details in local storage as soon as user logs in successfully.
So with that, we must check the userName in local storage first and based on that we must do the further operation.
ngOnInit() {
const status = this.checkUserNameInLocalStorage();
if (status) {
this.userName = JSON.parse(window.localStorage['userName']);
} else {
// write your logic to get the userName details
}
}
checkUserNameInLocalStorage() {
if (window.localStorage['userName']) {
return true;
} else {
return false;
}
}
Hope this will help you.
Upvotes: 1