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

How can Material UI React handle long strings in menu text wrapping for both mobile and desktop devices?

Is there a way to ensure that long strings in an MUI Select component do not exceed the width and get cut off on mobile devices? How can I add a text-wrap or similar feature? Desktop: Mobile: <FormControl sx={{ m: 1, minWidth: '100%', marg ...

Using Generic Types in TypeScript for Conditional Logic

To better illustrate my goal, I will use code: Let's start with two classes: Shoe and Dress class Shoe { constructor(public size: number){} } class Dress { constructor(public style: string){} } I need a generic box that can hold either a ...

The interfaced JSON object did not return any defined value

I am working on implementing a pipe in Angular 9 that will handle the translation of my table words into different languages. To achieve this, I have set up a JSON file with key-value pairs for translation services and created corresponding interfaces for ...

Setting a default value for a complex prop in Vue through Type-based props declarations

I'm struggling with this issue: Argument of type 'HelloWorldProps' is not assignable to parameter of type 'InferDefaults<LooseRequired<HelloWorldProps>>'. Types of property 'complexProp' are incompatible.ts( ...

Sending text containing HTML elements from the parent component to the child component

I'm facing a challenge where I need to transfer a string from my parent component to my child component. The string includes HTML tags with an HTML entity. Here's how it looks in the parent template: <child-component i18n-componentContent=&quo ...

What's the best approach for revalidating data with mutate in SWR?

Whenever a new album is created in my app, the post request response includes an updated list of all albums. To enhance the user experience, I wanted the newly created content to automatically show up without requiring a page refresh. Although I am famil ...

What is the best approach to converting an array of strings into a TypeScript type map with keys corresponding to specific types?

The code provided below is currently working without any type errors: type Events = { SOME_EVENT: number; OTHER_EVENT: string } interface EventEmitter<EventTypes> { on<K extends keyof EventTypes>(s: K, listener: (v: EventTypes[K]) => voi ...

Cypress: Uncovering the method invoked by a button click

I'm currently utilizing Vue3 with Vite and Cypress. My Vue3 component utilizes the script setup SFC syntax. Below is the code snippet for my component: <template> <div> <button data-cy="testBtn" @click="btnClick()&q ...

The issue arises where Google Maps Platform rejects your request due to an invalid request with an unexpected parameter "amp%3Bkey"

Dealing with angular error Your request has been rejected by Google Maps Platform. It was flagged as invalid due to an unexpected parameter 'amp%3Bkey'. Here's the error displayed in the console: GET https://www.google.com/maps/embe ...

Injecting Dependencies in Angular 2

In order to streamline my data services, I have decided to create a base class. This base class contains common functions such as post, get, and exception handling. By having the derived classes inherit from the base class, they can easily access these fun ...

TypeORM: Create case-insensitive search functionality

Creating a basic search feature where the records are as follows: AB CD A BCD ABC D ABD C If the search term is "BCD", the expected output should be: AB CD A BCD ABC D The current query looks like this: await connection.manager .createQueryBuilder(RefTra ...

Tips for limiting users to inputting only alphanumeric characters and excluding special characters in an input field using Angular 8

How can I prevent users from inputting special characters in an input field and only allow alphanumeric values? The code that I have implemented so far does not seem to be working as intended. When a user enters a special character, it still shows up in th ...

Encountering obstacles when attempting to initiate a node application due to an error

Upon starting my node application, I encountered an error. The error message reads: "ERROR in Metadata version mismatch for module ../node_modules/@ng-bootstrap/ng-bootstrap/index.d.ts, found version 4, expected 3" Here is the full error trace: ERROR ...

Steps to converting an enum or literal

Hey there, I'm relatively new to working with TypeScript and I've been experimenting with transforming enums/literals using functions. For instance, creating a capitalize function that capitalizes the first letter of a string. (e.g., mapping typ ...

Error in TypeScript: Objects can only specify properties that are known, and 'state' is not found in type 'Partial<Path>'

As I strive to pass props through a React Router Link, my goal is to include all the user props. The code below is causing an error, particularly where state: {...employee} is highlighted. Although I am relatively new to TypeScript, I am actively working ...

Encountering an issue when using npm to add a forked repository as a required package

While attempting to install my fork of a repository, I encountered the error message "Can't install github:<repo>: Missing package name." The original repository can be accessed here, but the specific section I am modifying in my fork is located ...

Is the "Angular is not functioning" error message the result of a missing import?

Encountering an 'is not a function' error in Angular 7 / TypeScript 3, using an EventEmitter. This issue has been extensively discussed (a b), but solutions have not garnered many upvotes (a b c d e f). I am close to resolving it, but need s ...

The React component fails to load due to the discrepancies in the data retrieved from various asynchronous requests

Creating a travel-related form using React with TypeScript. The initial component TravelForm utilizes multiple async-await requests within useEffect hook to update the state of the subsequent component TravelGuideFields However, the values of props a ...

Creation of source map for Ionic 2 TypeScript not successful

Struggling with debugging my Ionic 2 application and in need of guidance on how to include souceMap for each typescript file that corresponds to the javascript files. Despite enabling "sourceMap":true in my tsconfig.json file, the dev tools in Chrome do n ...

The application is experiencing extended loading times during production

After deploying my Angular 2 app on Heroku, I've noticed that it's taking a long time to load. Is there a way to bundle everything up instead of having all the scripts and stylesheets scattered across my index.html file? <html> <head> ...