What is the proper way to utilize a class with conditional export within the Angular app.module?

This query marks the initiation of the narrative for those seeking a deeper understanding.

In an attempt to incorporate this class into app.module:

import { Injectable } from '@angular/core';
import { KeycloakService } from 'keycloak-angular';
import { environment } from '../../../environments/environment';

@Injectable({ providedIn: 'root' })
export class MockKeycloakService { 

    init(ign: any) {
        console.log('[KEYCLOAK] Mocked Keycloak call');
        return Promise.resolve(true);
    }

    getKeycloakInstance() {
        return {
            loadUserInfo: () => {
                let callback;
                Promise.resolve().then(() => {
                    callback({
                    username: '111111111-11',
                    name: 'Whatever Something de Paula',
                    email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="37405f56435241524577505a565e5b1954585a">[email protected]</a>',
                  });
                });
                return { success: (fn) => callback = fn };
            }
        } as any;
    }    
    login() {}      
    logout() {}
}

const exportKeycloak = 
    environment.production ? KeycloakService : MockKeycloakService;    
export default exportKeycloak; 

This conditional exporting allows for a fake keycloak call in local development and switches to the actual class in production mode.

The following app.module was utilized:

<...>
import { KeycloakAngularModule } from 'keycloak-angular';
import KeycloakService from './shared/services/keycloak-mock.service';
import { initializer } from './app-init';
<...>

    imports: [
        KeycloakAngularModule,
         <...>  
    ],
    providers: [
        <...>,
        {
            provide: APP_INITIALIZER,
            useFactory: initializer,
            multi: true,
            deps: [KeycloakService, <...>]
        },
        <...>
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

Corresponding app-init:

import KeycloakService from './shared/services/keycloak.mock.service';
import { KeycloakUser } from './shared/models/keycloakUser';

import { environment } from '../environments/environment';
<...>

export function initializer(
    keycloak: any,
    <...>
): () => Promise<any> {
    return (): Promise<any> => {
        return new Promise(async (res, rej) => {
            <...>    
            await keycloak.init({
                 <...>
            }).then((authenticated: boolean) => {
                if (!authenticated) return;
                keycloak
                    .getKeycloakInstance()
                    .loadUserInfo()
                    .success(async (user: KeycloakUser) => {
                        <...>
                    })    
            }).catch((err: any) => rej(err));
            res();
        });
    };

Everything functions properly in development mode. I am able to utilize the mock call, and upon enabling production mode in the environment configuration, the real call is made. However, when attempting to compile for deployment on a production server, the following error occurs:

ERROR in Can't resolve all parameters for ɵ1 in /vagrant/frontend/src/app/app.module.ts: (?, [object Object], [object Object]).

It seems that the build task fails to comprehend the conditional export in the mocked class for use in app.module.

As a result, I am required to include both classes in app-init and other areas where it is used, checking for the environment mode in each instance. It would be more efficient if I could simply utilize a single class to handle this scenario and import it wherever necessary.

Here is my build command:

ng build --prod=true --configuration=production --delete-output-path --output-path=dist/

How can I address this error during the build process? Furthermore, why does everything function smoothly in development mode while encountering discrepancies during the build?

Answer №1

It appears that you are working with Angular 8 or an earlier version.

In those particular versions, the AOT compiler does not have the capability to resolve references to default exports.

Therefore, it is recommended to be more specific:

keycloak-mock.service.ts

const KeycloakServiceImpl =
  environment.production ? KeycloakService : MockKeycloakService;
export { KeycloakServiceImpl };

app.module.ts

import { KeycloakServiceImpl } from './keycloak-mock.service';

...
deps: [KeycloakServiceImpl]

Pro Tip:

ng build --prod is the same as using

ng build --prod=true --configuration=production

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

What is the best way to deliver a file in Go if the URL does not correspond to any defined pattern?

I am in the process of developing a Single Page Application using Angular 2 and Go. When it comes to routing in Angular, I have encountered an issue. For example, if I visit http://example.com/, Go serves me the index.html file as intended with this code: ...

Dynamic views loaded from ui-router can cause compatibility issues with running Javascript

Currently, I am facing an issue while attempting to load a template into a UI-View using UI-Router. Although the JavaScript is loaded, it does not run on the loaded views. The situation unfolds as follows: I have developed a template in HTML containing all ...

How can I extract the return value of a JSON object and store it in a variable?

I am attempting to develop a dynamic chart by utilizing data retrieved from a function housed inside a JSON object. The JSON object is fetched through the Relayr Javascript API, and looks like this: relayr.devices().getDeviceData({ token: tok ...

Encountering an issue with the property name despite already defining it

Encountering a property name error even though it has been defined Uncaught (in promise): TypeError: Cannot read property 'nome' of undefined export class HomePage { inscricao = "São Bernardo"; nome = "abc"; nomeInvalido; construc ...

Ways to invoke main.ts to communicate with an Angular component using Electron

I have a good understanding of how to communicate between an angular app and the electron main thread using IPC. However, in my current scenario, I have threads running in the electron main thread for video processing. After these threads complete their t ...

SvgIcon is not a recognized element within the JSX syntax

Encountering a frustrating TypeScript error in an Electron React App, using MUI and MUI Icons. Although it's not halting the build process, I'm determined to resolve it as it's causing issues with defining props for icons. In a previous pro ...

Vuetify Autocomplete that allows for adding values not in the predefined list

I am utilizing a vuetify autocomplete component to showcase a list of names for users to select from. In the case where a user enters a name not on the list, I want to ensure that value is still accepted. Check out my code snippet below: <v-autocomplete ...

Acquire the content of a nested element using jQuery

I have a navigation list with separate headlines and text for each item. The goal is to switch the main headline and paragraph of text when hovering over a navigation item. CodePen Example Currently, my code displays all text. I only want to display the ...

The map buttons are located underneath the map, and unfortunately, it seems that setting the map height to 100% using Angular is

Upon completing the creation and display of the map, an unusual occurrence is taking place where the map buttons ("Zoom rectangular, map settings, and scale bar") are appearing below the map as oversized icons. Additionally, there is a challenge when setti ...

Shift the Kid Element to an Alternate Holder

Currently, I am working on a project in Angular version 10. Within this app, there is a component that can be shared and will utilize the provided content through ng-content. Typically, this content will consist of a list of items such as divs or buttons. ...

Angular directive does not focus on the text box

I've been working on creating text boxes using a directive and I want only the first text box to be in focus. To achieve this, I am utilizing another directive for focus control. Below is my script: <script> angular.module('MyApp',[]) ...

"Utilizing AngularJS to asynchronously send an HTTP POST request and dynamically update

I've been working on an angularjs chat module and have come across a challenge. I developed an algorithm that handles creating new chats, with the following steps: Click on the 'New Chat' button A list of available people to chat with wil ...

Unexpected results occurring during JavaScript refactoring process

Having this repetitive code snippet that switches between two radio buttons being checked within my $(document).ready(): $(document).ready(function () { $("#New").click(function () { var toggleOn = $("#New"); var tog ...

The setInterval function does not function properly in IE8 when set to 0

I have a function called changeColor that updates the styling of certain elements in my HTML. In order to apply this function, I am using a timer like so: var timer = setInterval(changeColor,0); The issue I am encountering is that setting the time interv ...

Button click initiates DataTables search rather than manually entering text in the input field

I am exploring the option of relocating the search function from an input to a button for a table that has been modified using DataTables. Currently, I have a customized input that triggers this function: <script> $(document).ready(function() { ...

Unable to establish a new pathway in the index.js file of a Node.js and Express website running on Heroku

I recently made some changes to my index.js file: const express = require('express'); const path = require('path'); const generatePassword = require('password-generator'); const fetch = require('node-fetch'); const ...

Attempting to create a login feature using phpMyAdmin in Ionic framework

Currently, I am in the process of developing a login feature for my mobile application using Ionic. I am facing some difficulties with sending data from Ionic to PHP and I can't seem to figure out what the issue is. This is how the HTML form looks li ...

Display the HTML/CSS layout following the JavaScript window.open action

Encountering issues with printing output in an opened window using JavaScript. I'm creating a new document through window.open and including CDN links to Bootstrap files. While everything appears fine in the opened window, when attempting to print (XP ...

conceal the .card-body element if the children have the CSS property "display:none"

My challenge involves managing two collapsible cards on a webpage. I am looking for a solution where the .card-body will have its display set to none when there are no inner divs to show in the card upon clicking a letter in the pagination. Otherwise, the ...

Elementary component placed in a single line

Creating a text dropdown menu using the following code: import { Autocomplete, TextField } from '@mui/material' import React, { useState } from 'react' const options = [ 'Never', 'Every Minute', 'Every 2 ...