Issue with Angular and OIDC - user data is missing upon logging in

I am in the process of developing an application using Angular along with IdentityServer as the Single Sign-On (SSO) provider in ASP.NET.

After successfully logging in and retrieving user information from the authentication server: User info

The following method is triggered when the SSO redirects the user back after logging in (the displayed user info is from the previous image):

//Auth service
async completeAuthentication()
  {
    this.user = await this.manager.signinRedirectCallback();
    console.log(this.user);
    this.authNavStatusSource.next(this.isAuthenticated());
  }

Although I have defined the user at this point, when attempting to use the user's username in the header, it appears as undefined: Undefined user

This is where the console.log is triggered:

//Header component
ngOnInit(): void {
    this.subscription = this.authService.authNavStatus$.subscribe(status => this.isAuthenticated = status);
    this.name = this.authService.username;
  }

//Auth service
get username(): string
  {
    console.log(this.user);
    return this.user != null ? this.user.profile.preferred_username : '';
  }

For reference, here are the full files for the auth service and header component:

auth.service.ts

import { Injectable } from '@angular/core';
import { UserManager, User } from 'oidc-client';
import { BehaviorSubject } from 'rxjs';
import { BaseService } from '../services/base.service';
import { ConfigService } from '../services/config.service';

@Injectable({
  providedIn: 'root'
})
export class AuthService extends BaseService {

  // Implementation details omitted for brevity
}
header.component.ts

import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
import { AuthService } from '../core/authentication/auth.service';

@Component({
  selector: 'app-header',
  template: `
    <!-- Template content omitted for brevity -->
  `,
  styles: [ 
    '.navbar{ border-style: solid; border-width: 0px 0px 2px 0px; }'
  ]
})
export class HeaderComponent implements OnInit, OnDestroy {

  // Member variables and methods implementation omitted for brevity
}

Despite utilizing the same get username() method in the home component successfully, why am I unable to access the user in my header component? It's perplexing that it works in one place but not the other.

Answer №1

It seems possible to utilize username in the header. The issue may arise if it is being used before it is properly initialized.

One potential solution could be to include the this.name assignment within the subscription block like so:

this.subscription = this.authService.authNavStatus$
.subscribe(
   status => {this.isAuthenticated = status;
   this.name = this.authService.username;
});
    

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

Creating a JSON structure using an array in Typescript

Here is an example of my array structure: [ { "detail": "item1", "status": "active", "data": "item1_data" }, { "detail": "item2", "status": ...

Using a dropdown list to filter values in a table with Angular ngBootstrap

Seeking assistance with filtering table values based on the selected filter. I plan to utilize this ngbDropdown as my filter. If I choose company A, only entries related to company A will be displayed in the table. I am unsure about how to connect the f ...

Setting up a routerLink from a component

My current routing is functioning well, however, I am interested in managing the same functionality from a component rather than directly in the HTML. How can I achieve this? HTML <a [routerLink]="[ '..', card.item ]">VIEW MORE</a> ...

Struggling to modify a string within my React component when the state is updated

Having a string representing my file name passed to the react-csv CSVLink<> component, I initially define it as "my-data.csv". When trying to update it with data from an axios request, I realize I may not fully understand how these react components w ...

Issues arise when Typescript's declaration merging feature does not function correctly when utilizing ts-node

I am currently working on a project that involves using the express-session package. My goal is to modify the session object by adding a user key. req.session.user = 123; After reading through the accepted answer in this question, I learned about declarat ...

What is the process of defining a callback function in Typescript?

Here is a function that I am working with: .add({a: 1, b: 2}, function (msg, reply) { reply({z: msg.z}) }) I attempted something like this: interface SenecaMethods { add: (pattern: object, CALLBACK NEEDS TO BE INSERTED HERE) => object; } ...

Steer clear of receiving null values from asynchronous requests running in the background

When a user logs in, I have a request that retrieves a large dataset which takes around 15 seconds to return. My goal is to make this request upon login so that when the user navigates to the page where this data is loaded, they can either see it instantly ...

Employing ngModel within an (click) event in Angular 4

I have this html code snippet: <div class="workflow-row"> <input type="checkbox" id="new-workflow" [(ngModel)]="new_checkbox"> <label>New Workflow</label> <input type="text" *ngIf="new_checkbox" placeholder="Enter ...

When a reaction function is triggered within a context, it will output four logs to the console and

My pokemon API application is encountering some issues. Firstly, when I attempt to fetch a pokemon, it continuously adds an infinite number of the same pokemon with just one request. Secondly, if I try to input something again, the application freezes enti ...

Retrieve the mfData value from the TypeScript file in order to perform operations on it within the Angular 2 framework

I have a snippet of code that iterates through data from stacklist_table, which is a JSON array, and displays it in a table format. The stacklist_table contains a full list of objects, but I only need a subset of these objects so I have applied some filter ...

Warning from React 17: Unexpected presence of <a> tag inside <div> tag in server-rendered HTML

I've checked out the existing solutions and still can't seem to make it work. components/NavBar.tsx import { Box, Link } from "@chakra-ui/react"; import { FunctionComponent } from "react"; import NextLink from "next/link ...

What is the best way to exceed the capacity of a function in TypeScript by incorporating optional

I've been working on converting some code from JavaScript to TypeScript, and I have a specific requirement for the return type of a function. The function should return void if a callback parameter is provided, otherwise it should return Promise<o ...

Using ngModel to retrieve and display only the month, year, and date

Currently, I am working with an interface named Person which includes fields such as name, last name, birthday, and others. However, I am facing a confusion when it comes to the person's birthday format, as it contains some additional letters at the e ...

How to form an array of arrays within an object using Angular framework

I'm struggling to find the optimal solution and could use some guidance. Objective There are 4 separate multiple select drop-down menus, and users can choose any combination of values from each drop-down to create a box (limited to 7 selections) by ...

Can you explain the purpose of the curly braces found in a function's parameter definition?

I am currently working on an Angular 5 project and came across this intriguing Typescript code snippet. (method) CreateFlightComponent.handleSave({ currentValue, stepIndex }: { currentValue: Partial<Flight>; stepIndex: number; }): void Can ...

Efficiently loading Ionic 3 components within a tab with lazy-loading functionality

Need help with adding a new tab to your project using lazy-loading? You can utilize the @IonicPage decorator for setting up a page as the root of a tab. To implement this, create a new page: // module import { NgModule } from '@angular/core'; ...

Typescript and the way it handles responses from REST APIs

Starting off, I must mention that I am relatively new to TypeScript, although I have been a JavaScript developer for quite some time. I am in the process of transitioning my existing JavaScript application to TypeScript. In the current JavaScript app, the ...

Encountering an "Invalid hook call error" while utilizing my custom library with styled-components

I recently developed my own custom UI tool using the styled-components library, integrating typescript and rollup for efficiency. One of the components I created looks like this: import styled from 'styled-components' export const MyUITest2 = s ...

How to customize the color of md-radio-button in Angular?

I've been trying to customize the color of my radio buttons, but I haven't had much luck. Here are a couple of examples I attempted: Example 1 HTML <md-radio-button class"radio-button"> yes <md-radio-button> CSS //checked .radio- ...

Some code paths fail to return a value in Google Cloud Function callable functions

When utilizing async functions in my cloud function and including a 'return' statement in each potential output, I am still encountering the error message Not all code paths return a value I attempted removing my database calls and only leaving ...