I am trying to use sessionStorage to store user information which is retrieved at ngInit of AppComponent. But as this retrieval uses httpClient, it is like to be accessed in another component even before the key value is stored. This is the only time this key will be set.
@Injectable()
export class AuthService {
public currentuser = new BehaviorSubject<User>(<User>JSON.parse(sessionStorage.getItem('currentuser')));
constructor(private _http: HttpClient, private _trace: TraceService) { }
public authenticate(): void {
this._http.get<User>(AppSettings.AuthUrl, {withCredentials: true})
.subscribe(user => {
sessionStorage.setItem('currentuser', JSON.stringify(user));
this.currentuser.next(user);
},
e => {
if (e.status === 403) {
this.currentuser.next(null);
this._trace.handleAuthError(e);
} else {
this.currentuser.next(null);
this._trace.handleError('Authenticating...', e);
}
});
}
}
In auth guard component I have
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private _router: Router,
private _authService: AuthService) { }
public canActivate() {
this._authService.currentuser.subscribe(u => {
if (u === null) {
this._router.navigateByUrl(AppSettings.NotAuthenticatedRoute);
return false;
}});
return true;
}
}
routing module
const routes: Routes = [ { path: AppSettings.LegalTermsRoute, component: LegalTermComponent, canActivate: [AuthGuard] }];
In AppComponent
ngOnInit(): void {
this._authService.authenticate();
}
The issue is that I am not not setting this subscription the right way the auth guard blocks the LegalTermComponent when the app comes up