How to get userprofile from keycloak in angular - Stack Overflow

admin2025-04-21  2

I am using latest angular version. Below is code of my keycloak.service.ts. I am trying to retrieve the user's email, but the value is coming back as empty. However, when I check the profile inside the .then() block, I can see the profile details logged in the console. I will greatly appreciate any help.

    import { Injectable } from '@angular/core';
    import { BehaviorSubject, Observable } from 'rxjs';
    import { filter, map, tap } from 'rxjs/operators';
    import Keycloak, { KeycloakInstance, KeycloakProfile } from 'keycloak-js';
    
    @Injectable({
      providedIn: 'root',
    })
    export class KeycloakService {
      private keycloakInstance: KeycloakInstance = new Keycloak({
        url: 'http://localhost:9090',
        realm: 'book-social-network',
        clientId: 'angular-app',
      });
    
      private userProfileSubject = new BehaviorSubject<KeycloakProfile | null>(null);
    
      init(): Promise<boolean> {
        return this.keycloakInstance
          .init({
            onLoad: 'login-required',
            checkLoginIframe: false,
          })
          .then((authenticated: boolean) => {
            if (authenticated) {
              return this.keycloakInstance.loadUserProfile().then((profile) => {
                console.log('Profile fetched successfully:', profile); // Log fetched profile
                this.userProfileSubject.next(profile); // Emit profile
                console.log('After emitting profile:', this.userProfileSubject.value); // Log BehaviorSubject value
                return true;
              });
            } else {
              console.log('Not authenticated');
              return false;
            }
          })
          .catch((err) => {
            console.error('Keycloak initialization failed:', err);
            return false;
          });
      }
    
      getUserProfile(): Observable<KeycloakProfile> {
        return this.userProfileSubject.asObservable().pipe(
          filter((profile): profile is KeycloakProfile => profile !== null) // Filter out null
        );
      }
    
      getUseremail(): Observable<string | null> {
        return this.getUserProfile().pipe(
          map((profile) => profile.email || null), // Map profile to email
          tap((email) => console.log('Emitting email:', email)) // Log the email being emitted
        );
      }
    }

I am using latest angular version. Below is code of my keycloak.service.ts. I am trying to retrieve the user's email, but the value is coming back as empty. However, when I check the profile inside the .then() block, I can see the profile details logged in the console. I will greatly appreciate any help.

    import { Injectable } from '@angular/core';
    import { BehaviorSubject, Observable } from 'rxjs';
    import { filter, map, tap } from 'rxjs/operators';
    import Keycloak, { KeycloakInstance, KeycloakProfile } from 'keycloak-js';
    
    @Injectable({
      providedIn: 'root',
    })
    export class KeycloakService {
      private keycloakInstance: KeycloakInstance = new Keycloak({
        url: 'http://localhost:9090',
        realm: 'book-social-network',
        clientId: 'angular-app',
      });
    
      private userProfileSubject = new BehaviorSubject<KeycloakProfile | null>(null);
    
      init(): Promise<boolean> {
        return this.keycloakInstance
          .init({
            onLoad: 'login-required',
            checkLoginIframe: false,
          })
          .then((authenticated: boolean) => {
            if (authenticated) {
              return this.keycloakInstance.loadUserProfile().then((profile) => {
                console.log('Profile fetched successfully:', profile); // Log fetched profile
                this.userProfileSubject.next(profile); // Emit profile
                console.log('After emitting profile:', this.userProfileSubject.value); // Log BehaviorSubject value
                return true;
              });
            } else {
              console.log('Not authenticated');
              return false;
            }
          })
          .catch((err) => {
            console.error('Keycloak initialization failed:', err);
            return false;
          });
      }
    
      getUserProfile(): Observable<KeycloakProfile> {
        return this.userProfileSubject.asObservable().pipe(
          filter((profile): profile is KeycloakProfile => profile !== null) // Filter out null
        );
      }
    
      getUseremail(): Observable<string | null> {
        return this.getUserProfile().pipe(
          map((profile) => profile.email || null), // Map profile to email
          tap((email) => console.log('Emitting email:', email)) // Log the email being emitted
        );
      }
    }
Share Improve this question edited Jan 24 at 9:25 ahuemmer 2,05913 gold badges27 silver badges36 bronze badges asked Jan 22 at 23:56 AliAli 313 bronze badges 1
  • I think you just forget .subscribe() when try to get email – SergeyChe Commented Jan 23 at 6:16
Add a comment  | 

1 Answer 1

Reset to default 1

Since you are using Angular, I recommend you to use a library that integrates Keycloak services within a proper dependency injection context.

Instead of using keycloak-js, you could try keycloak-angular for a more seamless integration.

Here's an example of code I used in a previous project—it might give you some ideas to help resolve your issue:

转载请注明原文地址:http://anycun.com/QandA/1745223370a90425.html