Eroor on angular login using keycloak

19 views
Skip to first unread message

Belguitidh X

unread,
May 20, 2024, 1:22:12 PMMay 20
to Angular and AngularJS discussion
hey everyone ,
my probeleme is i'm not able to logout using keycloak , the login is work but logout always display this error for me .
 ERROR TypeError: Cannot read properties of undefined (reading 'logout')
    at _KeycloakService.<anonymous> (keycloak-angular.mjs:147:26)
my code : 

export class AppComponent implements OnInit {
  userProfile: any;
  isLoggedIn = false;

  constructor(private keycloakService: KeycloakService) {}

  ngOnInit() {
    // Check if user is already logged in on initialization
    this.isLoggedIn = this.keycloakService.isLoggedIn();
    console.log("you are logged");
    if (this.isLoggedIn) {
      this.retrieveUserProfile();
    }
  }

  async retrieveUserProfile() {
    try {
      const profile = await this.keycloakService.loadUserProfile(); // Use loadUserProfile()
      this.userProfile = profile;
    } catch (error) {
      console.error('Error retrieving user profile:', error);
    }
  }

  async onLogin() {
    try {
      await this.keycloakService.login(); // Perform Keycloak login flow
      this.isLoggedIn = true;
      this.retrieveUserProfile();
     
    } catch (error) {
      console.error('Login error:', error);
    }
  }

  async onLogout() {
    console.log('Logout e1');
    try {
      console.log('Logout e12');
       this.keycloakService.logout();
      this.isLoggedIn = false;
     this.isLoggedIn=false;
      this.userProfile = null;
     
    } catch (error) {
      console.error('Logout error:', error);
    }
  }
}


html code :
<div mat-icon-button [matMenuTriggerFor]="menu">
  <mat-icon *ngIf="userProfile">{{ userProfile.username }}</mat-icon>
  <button mat-icon-button *ngIf="!userProfile" >
    <mat-icon>login</mat-icon>
  </button>
</div>

<mat-menu #menu="matMenu">

  <button mat-icon-button *ngIf="userProfile" >
    <mat-icon>logout</mat-icon> {{ userProfile.username }}
  </button>
 
</mat-menu>
Reply all
Reply to author
Forward
0 new messages