I'm currently in the process of developing a service in Angular 12 that retrieves a "User" object, with OKTA being used for authentication.
My goal is to streamline the process. I can easily obtain the family name as an Observable using the following code snippet:
let familyName = this._oktaAuthStateService.authState$.pipe(
filter((authState: AuthState) => !!authState && !!authState),
map((authState: AuthState) => authState.idToken?.claims.family_name ?? '')
);
However, my desire is to pass just the string value itself instead of the entire observable.
For instance, I want to directly use the familyName variable without requiring the async pipe in HTML like below:
{{familyName | async}}
Here are my files for reference, acknowledging that they may be slightly messy.
user.service.ts
import {Inject, Injectable} from '@angular/core';
import {OKTA_AUTH, OktaAuthStateService} from '@okta/okta-angular';
import {filter, map, Observable, of, Subscription} from 'rxjs';
import {AccessToken, AuthState, OktaAuth} from '@okta/okta-auth-js';
import {User} from './data/user.model';
@Injectable({
providedIn: 'root'
})
export class UserService {
constructor(
private _oktaAuthStateService: OktaAuthStateService,
@Inject(OKTA_AUTH) private _oktaAuth: OktaAuth
) { }
get user(): Observable<any> {
let name = this._oktaAuthStateService.authState$.pipe(
filter((authState: AuthState) => !!authState && !!authState),
map((authState: AuthState) => authState.idToken?.claims.name ?? '')
);
// rest of the code unchanged...
return obsof5;
}
}
app.component.ts
import { Component, Inject, OnInit } from '@angular/core';
// remaining imports and declaration remain ...
app.component.html
<h1>Hello world - here's where you are</h1>
<p>Name: {{name | async}}</p>
<p>Email: {{email | async}}</p>
<p>FamilyName: {{familyName | async}}</p>
<p>GivenName: {{givenName | async}}</p>
<p>AccessToken: {{accessToken | async}}</p>
<p>Is Authenticated: {{isAuthenticated$ | async}}</p>