I am using BehaviorSubject to store user info on login. For some weird reason, the user info returned by BehaviorSubject is null
in AuthGuard that gets activated for my endpoint. Please help me understand what am I missing.
I have already tried to return the subject as observable, subcribe to the subject, ReplaySubject. Nothing seems to work and the user info is always null in auth guard. I have moved the AuthService provider declaration between app module and the service component. That also didn't help. Until the call goes to auth guard, the flow is normal where the user info is set. As soon as the auth guard is called, the user info is lost.
user reg: This is step where user logs in
onSubmit() {
this.document.location.href = environment.callbackUrl;
}
login component: This component sets the user info
this.authService.setUserInfo(user);
if (user.id_token!=null && user.role!=null && user.isLoggedIn){
this.router.navigate(['/view-main/datalogger-list']);
}
auth service
userSubject: BehaviorSubject<UserInfo> = new BehaviorSubject<UserInfo>(null);
setUserInfo(user: UserInfo){
if(user && user !=null){
this.userSubject.next(user);
}
}
getUserInfo() {
return this.userSubject.asObservable();
}
auth guard: here the user info is null
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
debugger
let userInfo:UserInfo;
this.authService.getUserInfo().subscribe(user => {
console.log('Evaluating in auth guard');
console.log('User: ', user);
//if user is logged in and role info is available from database.
if(user && user!=null
&& user.role!=null && user.role.trim().length>0
&& user.wwid!=null && user.wwid.trim().length>0){
// allow user
userInfo = user;
return true;
}
// TO-DO user logged in but do not have information from database -How i will knwo this?
else if(user && user!=null
&& user.wwid!=null && user.wwid.trim().length>0
&& (user.role==null || user.role=='undefined') ){
this.router.navigate(['welcome']);
return false;
}else{
// redirect user to oidc urls
this.router.navigate(['welcome']);
return false;
}
})
return false;
}
Expected: Return current user info Actual: Returns null
this.document.location.href = environment.callbackUrl;
I think this line is reloading the application from the ground up. Are you sure you are not experiencing a full reload? when navigating from one page to the other in Angular, you should use the Angular router. – A. ChiesasetUserInfo(user)
? – Daniel Habenicht