Transform OKTA Observable into a practical string variable

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>

Answer №1

1- Begin by declaring last_name : string; as well as

last_name$ : Observable<string>;
as global variables within the component's class.

2- Next, define last_name$ using a similar method to how isAuthorized$ was defined:

this.last_name$ = this._authService.authState$.pipe(...

3- Subscribe to last_name$ and assign the incoming value to last_name like so:

this.last_name$.subscribe(
  (lname) => { this.last_name = lname }
);

Now you have last_name$ as an observable and last_name as a regular string, allowing you to utilize them as needed.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering issues with upgrading Vue.js 2.5.2 with TypeScript

I am currently in the process of updating vue js to version 2.5.2 along with typescript 2.5.3. Below is my index.ts file: import Vue from 'vue' var app = new Vue({ el: '#app', data: { message: 'Hello Vue!' ...

Dealing with mistakes in an Angular service

I've been grappling with error handling in Angular. I attempted to handle errors within a service, but I'm uncertain if that's the correct approach. @Injectable({ providedIn: 'root', }) export class CaseListService { public con ...

What is the best way to bundle an Express server into an Electron application?

Currently in the process of developing an Electron app using vue-cli-electron-builder. My setup includes a local MySQL database and an Express server. I am wondering how to bundle my Express server with the Electron app? The Express server is used for d ...

When attempting to run npm install for @types/jquery, an error is returned stating "Invalid name: @types/jquery"

npm install @types/jquery npm ERR! Windows_NT 10.0.10586 npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-c ...

What is causing the extra space on the right side of the box?

I've been struggling to align text next to an image inside a box. Desired outcome CSS: #roundedBox { border-radius: 25px; background: #363636; width: auto; height: auto; margin: 10%; display: flex; position: relative; ...

The jQuery script designed to verify the page height doesn't appear to be functioning as intended

Below is a snippet of jQuery code that I'm working with: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script type="text/javascript"> hasVBar=""; hasHBar=""; $(docume ...

Issue: You cannot render objects as a React child element (object found with properties {name}). If you intended to display multiple children, consider using an array instead

I have just finished creating a new Provider and now I want to test it. To do this, I am setting up a mock Component within the test file. // TasksProvider.spec.tsx const task = { name: 'New Task', } function TestComponent() { const { tasks ...

Using Angular 5 to link date input to form field (reactive approach)

I'm encountering an issue with the input type date. I am trying to bind data from a component. Below is my field: <div class="col-md-6"> <label for="dateOfReport">Data zgłoszenia błędu:</label> <input type="date" formC ...

I'm looking to enhance security in my sign-up form by adding a custom shield using Angular for my Firebase database. How can

I recently followed a tutorial to build my angular app with firebase authentication. Currently, everything is functioning correctly. However, This is the first time I am attempting to create a genuine sign-up form with custom fields and integrate them i ...

Angular mat-select is having difficulty displaying options correctly on mobile devices or devices with narrow widths

In my Angular project, I've encountered an issue with mat-select when viewing options on mobile or low-resolution screens. While the options are still displayed, the text is mysteriously missing. I attempted to set the max width of the mat-option, but ...

Detecting if a click listener is registered within an Angular 2+ component

In the process of developing a reusable component featuring a rounded image thumbnail, I am aiming to incorporate functionality that detects if a click listener has been assigned to it. If a developer has applied a (click)=anyClickCallbackFunction() on the ...

The error message "npm ReferenceError: primordials is not defined (node.js)" indicates that the

I have encountered this issue multiple times and despite attempting various solutions, I am unable to resolve it. I am currently working with npm and facing the following error: evalmachine.<anonymous>:35 } = primordials; ^ ...

What is the best way to create a mapping function in JavaScript/TypeScript that accepts multiple dynamic variables as parameters?

Explaining my current situation might be a bit challenging. Essentially, I'm utilizing AWS Dynamodb to execute queries and aiming to present them in a chart using NGX-Charts in Angular4. The data that needs to appear in the chart should follow this fo ...

Failure of AJAX HTML function to retrieve value from textarea

I am displaying data in the first three columns of a table, with the last column reserved for user feedback/comments. However, when the form is submitted, the values in the textarea are not being posted. The table has 6 rows. The Sample TR: <tr> &l ...

Tips for turning off specific row elements within a formGroup in Angular

Hey there, I'm looking to disable a specific row that is selected through a checkbox. I've tried the code below but it's not working, so I could use some help with it. Thanks in advance! HTML file code: <form [formGroup]="myFormGroup"& ...

Introduction to Ajax communication using node.js

Currently, I am attempting to create a basic node.js server that takes in a request for a string, selects one randomly from an array, and returns the chosen string. However, I am encountering some challenges along the way. Here's what my front end lo ...

What is the best way to store all rows in a dynamically changing table with AngularJS?

I am facing an issue while trying to dynamically add rows for a variable that is a String array in my database. The problem is that it only saves the last value entered in the row instead of saving all of them in an array. Here is my current view code: &l ...

HTML is not connecting to CSS

I'm having trouble linking my external CSS to my HTML file. In the head of my index.html, I have this code: <head> <title>Twenty by HTML5 UP</title> <meta charset="utf-8" /> <meta name="viewport ...

What approach does JavaScript take when encountering a value that is undefined?

Having recently delved into JavaScript and exploring a book, I came across an interesting example in the recursive chapter: function findSolution(target) { function find(current, history) { if (current == target) return history; else if (c ...

What's the best way to organize a list while implementing List Rendering in VueJS?

Currently, I am working on List Rendering in Vue2. The list is rendering correctly, but it appears ordered based on the data arrangement in the array. For better organization, I need to sort each item alphabetically by title. However, I am facing difficult ...