Issue: "The current user authentication status is not defined."

Excuse my French, but here's my issue:

AppComponent.ts

import { Component, OnInit, HostListener } from '@angular/core';
import { environment } from '../environments/environment';
import { AuthOidcService, AuthUser } from '@cddng/auth-oidc-apim';
import { AuthService } from './service/auth.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  appName: string;
  authenticatedUser: AuthUser;

  constructor(private auth: AuthService, private oidcAuth: AuthOidcService) {
    this.appName = environment.application_name;
    this.oidcAuth.init(environment.auth_oidc_config);
  }

  ngOnInit() {
    this.oidcAuth.login();

    this.oidcAuth.oidcSecurityService.getIsAuthorized().subscribe((authorized: boolean) => {
      if (authorized) {
          this.authenticatedUser = this.oidcAuth.getAuthenticatedUserFromJwt();
      }
  });
  this.auth.idRh = this.authenticatedUser.idRh;
  this.auth.role = this.authenticatedUser.roles;
  console.log("*******************************************");
  console.log("idrh => " + this.auth.idRh);
  console.log("Roles => " + this.auth.role);
  console.log("isAdmin => " + this.auth.isAdmin);
  console.log("isExpert => " + this.auth.isExpert);
  console.log("isConsult => " + this.auth.isConsultation);
  console.log("*******************************************");

  }




  @HostListener('window:UserDisconnected') userDisconnected() {
    this.oidcAuth.corpHeaderLogout();
  }



}

The following error appears on the console:

ERROR TypeError: "this.authenticatedUser is undefined"

Refreshing the page resolves the issue, but not on first load

I suspect it's an asynchronous problem, but I'm unable to find a solution

Your insights are greatly appreciated

Answer №1

To properly utilize the functionality of subscribe, it is important to relocate the subsequent code lines within the scope of the subscribe method:

this.auth.idRh = this.authenticatedUser.idRh;
this.auth.role = this.authenticatedUser.roles;

Due to the asynchronous nature of the subscription process, it is crucial to ensure that you await the response before proceeding with any further actions.

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

Expanding the global object in ES6 modules to include TypeScript support for extensions like `Autodesk.Viewing.Extension`

I created a custom forge extension and now I am looking to incorporate typescript support as outlined in this blog post. However, I am facing an issue where typescript cannot locate the objects like Autodesk.Viewing.Extension and Autodesk.Viewing.ToolInter ...

Using React and TypeScript to conditionally set props in a component

I am trying to assign a value to the component's prop when a variable is defined. Below you can find my current code. import Cropper from 'react-easy-crop' ... interface State { ... coverFile: File | null; ... } class Test extends React ...

Using React with TypeScript to implement a nested map function

I have developed an application using React typescript, incorporating redux and saga for state management. The data fetched is displayed on the browser with Google Maps integration where hovering over properties displays them on the map. To enhance user ...

Tips for wrapping text in a column within material-ui's DataGrid

Struggling to apply word wrap to my column header title in DataGrid from material-ui. I've attempted using sx and style with no success. I even tried this: const StyledDataGridtwo = styled(DataGrid)<DataGridProps>(({ theme }) => ({ root: { ...

What is the best way to show the current date and time in an Angular template while ensuring it stays up to

I'm looking to showcase the current date and time in my angular template, and have it automatically refresh when the time changes. The desired application LOOKS as follows: This snippet is from my .html template: <div class="top-right pull-right ...

How does the kendo parseNumber function handle the input "NaN"?

Can anyone point me to the code for the Telerik Kendo Angular function parseNumber? I've noticed that it successfully parses "Infinity" but not "NaN", converting it to null. Any insights on why this happens and how it can be resolved? Thanks! ...

Exploring the integration of external javascript AMD Modules within Angular2 CLI

During my experience with Angular2 pre-releases, I found myself using systemjs to incorporate external JavaScript libraries like the ESRI ArcGIS JavaScript API, which operates on AMD modules (although typings are available). Now that I am looking to trans ...

The functionality of http.delete is smooth when tested on Postman, but encountering issues on Angular 4/Ionic 3 application

I am new to working with the Angular 2/Spring boot stack, so please bear with me as I navigate through this. I have implemented an http.delete method for deleting a specific row selected by the user with a confirmation alert. While the API request works p ...

Error message: Unable to assign value to 'kind' property as it is undefined in Angular Webpack application

Unexpectedly, my Angular application is encountering an error during the build process. TypeError: C:\Users\c\dev\privacy\node_modules\@fortawesome\angular-fontawesome\fesm2020\angular-fontawesome.mjs: Cannot se ...

Navigating back to previous pages in an Angular(6) project connected to a Firebase Firestore database is a common requirement for

While there is an abundance of resources on how to paginate to the next page when using Angular with Cloud Firestore (Firebase), I have been unable to find a solution for pagination to a previous page. The closest I have come is returning to the first page ...

I'm encountering an issue with my Angular 8 function not running, and I'm unsure of the reason behind it as there are no error messages appearing

Here is a function that I have: Join(movementId: string, movement: Movement, userId: string) { let fetchedUserId: string; let userList = []; fetchedUserId = userId; userList = movement.userList; userList.push(fetchedUserId); movement.userList ...

Setting a class for an HTML element within an ngFor loop

<div class="weather-app-wrapper" *ngIf="weather !== undefined"> <div class="weather-wrapper" *ngFor="let forecast of weather.forecastDays"> <div class="weather-card"> <div class="forecast-icon" [ngClass]="{{fore ...

What is the process for retrieving the API configuration for my admin website to incorporate into the Signin Page?

My admin website has a configuration set up that dynamically updates changes made, including the API. However, I want to avoid hardcoding the base URL for flexibility. How can I achieve this? Please see my admin page with the config settings: https://i.st ...

The function navigator.canShare() encountered a permissions denial while running in Typescript

Currently, I am in the process of developing an Angular8 PWA and have successfully implemented webshare to share text content. To my excitement, Chrome has now extended its support for file sharing starting from May 2019. However, while attempting to int ...

What sets apart a template reference variable (#) from [(ngModel)]?

While undergoing the tutorials and reviewing the documentation, I encountered the concept of `Template reference variables`. Despite my understanding of `NgModel` for two-way binding, I'm perplexed about the usage of `Template reference variables` in ...

The 'ngIf' property cannot be bound to 'div' since it is not recognized as a known property in the production build

When running locally, everything works fine. However, when moving to the production build, errors start popping up. The code snippet in question is: import { CommonModule } from '@angular/common'; imports: [ CommonModule ] The complete ...

Angular recognizing string-array type as a string input is not correct

I am encountering a challenge with an Angular CLI component that involves working with an array of strings called "searchResult": export class ParentComponent implements OnInit { mockArray: string[] = []; searchString: string = ''; searchR ...

How to use Angular2 Router to redirect a state to its default substate

How can we implement a default substate in the new Angular2 Router? For instance, I would like the router to automatically direct from /user to /user/profile, creating a default substate for user. ...

Exploring TypeScript <T that belongs to any array>

getLength function appears to be functional Upon inspection, these two functions seem quite similar (The second one may be more versatile as it can handle objects with properties other than just arrays): During runtime, both functions essentially transla ...

Whoops! Looks like there was a hiccup with the Vercel Deployment Edge Function, causing an

Every time I attempt to send a POST request to my Edge Function on Vercel Deployment, I encounter the following error message: [POST] /api/openai reason=EDGE_FUNCTION_INVOCATION_FAILED, status=500, user_error=true TypeError: Illegal invocation at app/api/ ...