Jhipster - currently logged in user in Angular Frontend

Viewed 776

How can I get the currently logged in user (more exactly, I need his id) in the frontend of a Jhipster generated application ? The frontend is Angular.

I have seen some older answers using the Principal class, but it seems that doesn't exist anymore.

Can anyone help ?

1 Answers

You can get the current authentication state by calling accountService.getAuthenticationState(), this will return either null if the user is not logged in or an Account object otherwise.

Once you have the account you can grab the user login from it and call userService.find(login) which will return an object of type IUser. At this point you have all the info you need from the current user.

Example (not tested):

export class MyComponent implements OnInit {
  user!: IUser;

  constructor(
    private accountService: AccountService,
    private userService: UserService
  ){}

  ngOnInit(): void {
    this.accountService.getAuthenticationState().subscribe(
      account => {
        if (account){
          this.userService.find(account.login).subscribe(
            user => (this.user = user)
          );
        }
      }
    );
  }
...
Related