Hello,
I am currently authenticating and storing the user inside a signal. I am also storing guards associated to this user inside another signal in my auth.service.ts.
My code is working when I navigate from / to /anything-else because my app.component is calling authenticate()
But if I refresh the page with /anything-else it redirects me because user and guards are not defined yet.
This is my Auth Service:
public _userGuards = signal<Guard | null>(null);
public authenticate() : void {
this.http
.post<UserAccount>(authenticateUrl, null, { observe: 'response' })
.subscribe({
next: (response) => {
this._userAccount.set(response.body as UserAccount);
},
error: () => {
this._isAuthenticating.set(false);
// Error handling
},
complete: () => {
this._userGuards.set(this.getGuards());
// getGuards example: {canView: true, canEdit: false}
},
});
}```
And this is my guard:
```export class CanViewGuard implements CanActivate {
constructor(
private router: Router,
private readonly authService: AuthService
) {}
canActivate(): boolean {
this.authService.authenticate();
if (this.authService._userGuards().canView)
return true;
this.router.navigate(['unauthorized']);
}
}```
If I put ```this.authService.authenticate();``` inside an if block it is also not working.
Also, I tried to call authenticate with APP_INITIALIZER but it is still not working.
I think that I am missing something with Signals...