Retrieving the location.host parameter within NgModule

I am currently working on integrating Angular Adal for authenticating my application's admin interface with Azure AD. However, I have encountered a challenge with the redirectUri setting. My goal is to dynamically retrieve the current app's host (location.host) and use it as the base for the redirectUri parameter so that it always generates the correct callback URL when communicating with AD.

In an ideal scenario, my configuration in admin.module.ts would be structured like this:

MsAdalAngular6Module.forRoot({
  tenant: '[Removed]',
  clientId: '[Removed]',
  redirectUri: `https://${location.host}/admin`,
  endpoints: {
  },
  navigateToLoginRequestUrl: false,
  cacheLocation: 'localStorage',
  postLogoutRedirectUri: `https://${location.host}/logout`,
})

While this setup works perfectly in development mode, the issue arises during production builds due to Angular's AOT compilation process replacing location.host with null. Upon researching possible solutions, it was proposed to utilize an InjectionToken to resolve this value at runtime. Consequently, I've made adjustments in the admin.module.ts file prior to the @NgModule declaration :

const REDIRECT_URI = new InjectionToken<string>('REDIRECT_URI');

export function redirectUriFactory() {
  console.warn('redirect to', `https://${location.host}/admin`); //debug correct uri
  return `https://${location.host}/admin`
}

Subsequently, within my NgModule, I have implemented:

MsAdalAngular6Module.forRoot({
  tenant: '[Removed]',
  clientId: '[Removed]',
  redirectUri: REDIRECT_URI,
  endpoints: {
  },
  navigateToLoginRequestUrl: false,
  cacheLocation: 'localStorage',
  postLogoutRedirectUri: `https://${location.host}/logout`,
})

The provider section now includes the definition of REDIRECT_URI as shown below:

providers: [
...
  { provide: REDIRECT_URI, useFactory: redirectUriFactory }
]

However, I am encountering an error during authentication, as the RedirectUri is being passed as InjectionToken REDIRECT_URI instead of using the value generated by my redirectUriFactory function.

Is there a way to successfully retrieve the location.host within my admin.module.ts file?

Thank you!

Answer №1

It is important to note that the angular AOT compiler replaces the variable with null because location.host is not available during compilation. One solution to this issue is to opt for using the JIT compiler instead of the AOT compiler, as the variable should be accessible during JIT compilation. (Choosing compiler)

In addition, I find it challenging to pass the hostname to a redirect URL. If it were a function, you could easily create a function to handle this task. However, since it expects a property or variable, it becomes more complicated.

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

Using kotlinx.serialization to deserialize a JSON array into a sealed class

Stored as nested JSON arrays, my data is in rich text format. The plaintext of the string and annotations describing the formatting are stored in text tokens. At decode time, I aim to map the specific structure of these nested JSON arrays to a rich Kotlin ...

What could be causing the lack of updates in my SolidJS component when the data changes?

One of my components in SolidJS is an Artist page component. Here is a snippet of the code: export function Artist() { const params = useParams<{ id: string }>(); const [data, setData] = createSignal(null); createEffect(() => { fetchArti ...

What is the best way to refine React Component's props with Typescript?

My setup involves utilizing two specific components: Test and Subtest. The main functionality of the Test component is to provide visual enhancements and pass a portion of its props down to the Subtest component. Some props in the Subtest component are des ...

What is the best way to export a ReactTS component along with its children?

After importing the component, I proceed to declare a new component which will be a child for the invoked one. import { someComponent } from './someComponent'; This is how I export it: const anotherComponent = () => {...}; export { someCompon ...

Setting a default value for a null Select Option in React: a guide

I am currently working with an array of values and looping through them to display in a Select Option. <Form.Item label="Status"> <Select value={user.status} onChange={handleStatusChange} > ...

Is there a way to automatically re-run Angular unit tests when changes are made, perhaps through the

Apologies, I am having trouble figuring out how to phrase or search for this. Are you familiar with the concept of having unit tests running in a console window and automatically rerunning whenever changes are made and saved? I am interested in adding a ...

Is there a way to halt the automatic expansion of a mat-expansion-panel upon being clicked?

I have a specific requirement for managing the opening and closing of my mat-expansion-panel. In my implementation, I want to rely solely on the panel's [expanded] input property to control its state. To achieve this, I am using NGRX as my state manag ...

The Firebase storage percentChanges() method is throwing a NaN error

I want to create a Firebase storage service using an Angular client to handle user profile image uploads. This service should return two observables: uploadProgress$ and downloadUrl$. The uploadProgress$ observable will store the value from percentChanges ...

Preventing the (click) function from being activated during dragging in Angular 10

My div contains an openlayers map setup as shown below: <div id="map" (click)="getInfo($event)" class="map"></div> Whenever I drag my mouse to move around the map, the getInfo function is triggered. Is there a way to make it trigger only when ...

Tips for troubleshooting issues with the Angular CLI development server

When I run ng serve from the Angular CLI in development, I expect my application to be served locally with live reloading. Usually, I see a single [WDS] Live Reloading enabled. message in the console after loading my app in the browser. Issue at Hand: La ...

Typescript interface requiring both properties or none at all

I possess key-value pairs that must always be presented together in a set. Essentially, if I have one key with its value A:B, then there should also be another key with its value C:D. It is permissible for the object to contain neither pair as well. (An ex ...

Angular router.redirect is not able to pass variables as expected

I am facing an issue with the router redirect and template lifecycle while using Stripe checkout in my Angular 5 project. After a user signs up, I trigger the stripe checkout modal. Once the modal receives a payment source token, I perform some additional ...

TypeError: Unable to access the 'classify' property of an object that has not been defined (please save the ml5.js model first)

In my React app, I have set up ml5.js to train a model by clicking on one button and make predictions with another. However, I encounter an error when trying to test the model for the second time: TypeError: Cannot read property 'classify' of und ...

Troubleshooting Issue with Angular 5: Inability to Hide Elements for Non-Authenticated Users

Below is the code from app.component.html <nav class='navbar navbar-default'> <div class='container-fluid'> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-targ ...

Uploading Files with Django Rest Framework and Angular 2

I am working with Django Rest Framework and Angular 2 to implement a file upload feature. Below is my code structure for handling files. Can anyone point out where I might be going wrong? Any help is greatly appreciated. Thank you! Django file: view cla ...

Fixing the Unspecified addEventListener ErrorLearn how to resolve this error

Having recently started working with Angular, I encountered an issue with my addEventListener method not functioning as intended. My goal is to create a delete button that removes a specific array from my input. This array is nested within a mat-card tag a ...

TypeScript encounters a self-referencing type alias circularly

Encountering an issue with Typescript 3.6.3, specifically getting the error: Type alias 'JSONValue' circularly references itself. View code online here In need of assistance to resolve the circular reference in this specific version of TS (note ...

Creating Dynamic ion-card Elements in Typescript by Programmatically Changing Values

Currently, I am working on a basic app that retrieves posts from the server and displays them as cards on the screen. At this early stage, one of my main challenges is figuring out how to dynamically add ion-card elements with changing content and headers ...

Align item in center of remaining space within container using Material-UI React

I am relatively new to MUI and styling HTML components, and I have a query. I'm currently utilizing the Grid feature in my React project. My goal is to achieve something similar to this (image edited in Paint, alignment may not be accurate): https://i ...

"Using Angular and TypeScript to dynamically show or hide tabs based on the selected language on a website

When switching the language on the website, I want to display or hide a specific tab. If the language is set to German, then show the tab; if any other language is selected, hide it. Here's my code: ngOnInit(): void { this.translate.onLangChange.s ...