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

Monitoring user engagement using Socket.io and Firebase

In my Node/Express app, I am working on monitoring active users without using sessions. The app relies on an external API for handling JWT tokens that are directly passed to the client for storing and subsequent API requests. To track active users, I am u ...

Tips for animating a nested array using jQuery

I have a border that is 9x9 with lines, columns, and squares, similar to a Sudoku border. I want to animate it, but I encountered some issues when trying to run multiple animations simultaneously. To solve this problem, I decided to animate one array of el ...

Difficulty with the value binding issue on input text produced by *NgFor

When using *ngFor in Angular to loop over an array and generate input text elements bound to the values in the array, I'm encountering some issues. The value is not binding correctly when a user inputs something into the text field. I attempted to ru ...

How can we direct the user to another tab in Angular Mat Tab using a child component?

Within my Angular page, I have implemented 4 tabs using mat-tab. Each tab contains a child component that encapsulates smaller components to cater to the specific functionality of that tab. Now, I am faced with the challenge of navigating the user from a ...

Terminate all active service requests and retrieve only the outcomes from the most recent request

Is there a way to cancel ongoing requests and only retrieve the result of the latest request triggered by my service on the backend? Here's my current code: this.vehiclesService.getVehiclesByPage(currentState).subscribe(success => { this.c ...

The Node gracefully disconnects and apologizes: "I'm sorry, but I can't set headers after they have already

events.js:160 throw er; // Unhandled 'error' event ^ Error: Can't set headers after they are sent. register.js:20:18 register.js user.save(function(err) { if(err){ return mainFunctions.sendError(res, req, err, 500, ...

Implementing AngularJS within a standalone system devoid of internet connectivity

Hello there! I am interested in creating a single page web application for an embedded system that won't have access to the internet. This means I need to develop it without relying on external sources for functionality. Although I prefer AngularJS, ...

Enhance Your Tables with JQuery Calculations

I have a table that is populated from a database. Each field in the table is hidden until it is selected from a dropdown list. I also need to calculate the total of only the visible rows, not all rows including hidden ones. Can you please advise on how I c ...

Error encountered: Jquery counter plugin Uncaught TypeError

I am attempting to incorporate the JQuery Counter Plugin into my project, but I keep encountering an error: dashboard:694 Uncaught TypeError: $(...).counterUp is not a function <!DOCTYPE html> <html lang="en"> <head> <script src ...

Clicking on "Ng-Click" will add a fresh row to the table using Angular

Is there a way to insert a new row into a table using ng-click? I currently have the following setup with the data stored in an array. Here is how my array looks. $scope.workflows = [{ Id: 1, Name: "Workflow Page 1", ...

Identify the class within a child division and include the class in a separate division

How can I detect a special class within a child div and then add a class to another div when that specific class is found? For example: <ul class="m-a-ul"> <li class="menu"> </ul> Now, if the class collapsed is dynamically added: ...

I continue to encounter an error every time I attempt to place an HTML nested div on a separate line

When I structure the HTML like this, I don't encounter any errors: <div class="game-card"><div class="flipped"></div></div> However, if I format it differently, I receive an error message saying - Cannot set property 'vi ...

Node.js module mishap

In the package.json file I'm working with, these are the content of my dependencies: "devDependencies": { "chai": "^4.1.2", ... "truffle": "4.1.3" } A new NodeJS script called getWeb3Version.js was created: let web3 = require("web3" ...

Is Javascript Profiling a feature available in Firebug Lite?

Exploring the world of JavaScript profiles, I decided to step away from the usual Chrome Developer tools. Can Firebug Lite for Google Chrome provide Javascript Profiling functionality? ...

Steps for initiating an Angular 4 project

While most developers have moved on to Angular 5, I was tasked with creating a project using Angular 4. After conducting research for several days, I discovered that downgrading the Angular CLI would allow me to accomplish this. By following this approach, ...

Loading indicator for buttons

Issue with submit button onclick function (onClick="mandatoryNotes()"). It is taking a while to load, so a preloader script was added. The preloader is now working, but the function is not being called. Seeking assistance. Thank you. function mandatoryN ...

Master the art of adjusting chart width on angular-chart with the help of chart.js

I am currently using angular-chart along with Angular and chart.js to create multiple charts on a single page. However, I am facing an issue where each chart is taking up the entire width of the screen. I have tried various methods to limit the width based ...

Attempting to transform HTML code received from the server into an image, but encountering an error while using ReactJS

This app is designed to automate the process of creating social media posts. I have a template for the vertical "Cablgram" stored in the backend, and when I make a request, it returns the HTML code for that template. However, I encounter an error when tryi ...

Sorting JSON arrays in Typescript or Angular with a custom order

Is there a way to properly sort a JSON array in Angular? Here is the array for reference: {"title":"DEASDFS","Id":11}, {"title":"AASDBSC","Id":2}, {"title":"JDADKL","Id":6}, {"title":"MDASDNO","Id":3}, {"title":"GHFASDI","Id":15}, {"title":"HASDFAI","Id": ...

Obtain the last used row in column A of an Excel sheet using Javascript Excel API by mimicking the VBA function `Range("A104857

Currently in the process of converting a few VBA macros to Office Script and stumbled upon an interesting trick: lastRow_in_t = Worksheets("in_t").Range("A1048576").End(xlUp).Row How would one begin translating this line of code into Typescript/Office Scr ...