How to get userprofile from keycloak in angular

Discussão em 'Angular' iniciado por Ali, Janeiro 22, 2025.

  1. Ali

    Ali Guest

    I am using latest angular version & I am new to angular. Below is code of my keycloak.service.ts. When I try to get user email , I get nothing. However inside then , I could see profile in 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
    );
    }
    }

    Continue reading...

Compartilhe esta Página