Interactive loadChild components

I've been attempting to dynamically import routes from a configuration file using the following code snippet:

export function buildRoutes(options: any, router: Router, roles: string[]): Routes {
    const lazyRoutes: Routes = Object.keys(options)
        .map((key) => {
            const entry: RouteConf = options[key];
            const auth = entry.authRoute as string[];
            let output: Route =   {
                path: entry.routePath,
                redirectTo: 'fallback',
            };
            if (auth.some(item => roles.includes(item))){
                console.log(entry.exposedModule,entry.ngModuleName);
                output = {
                    path: entry.routePath,
                    loadChildren: () => import(entry.exposedModule).then((m) => m[entry.ngModuleName])
                }
             }
            return output;
        });

    return [...lazyRoutes,...APP_ROUTES ];
}

however, I'm encountering the following error:

ERROR Error: Uncaught (in promise): Error: Cannot find module '../richieste/richieste.module'
Error: Cannot find module '../richieste/richieste.module'

if I manually set the same data in the loadChildren, like this:

....
loadChildren: () => import( '../richieste/richieste.module').then((m) => m["RichiesteModule"])
....

everything works fine.

Is there a way to dynamically import modules for LazyLoading?

Thanks

Answer №1

A solution to the problem can be found by utilizing dynamic imports for Lazy Loading within your code. When employing dynamic imports, it is important to keep in mind that module paths are resolved relative to the location of the file containing the import statement. In this particular scenario, the value stored in entry.exposedModule contains a relative path ('../richieste/richieste.module'), which leads to an error due to the inability to locate the module.

To resolve this issue, you can utilize the import.meta.url property, which supplies the URL of the current module. Through combining import.meta.url with the new URL() function, it becomes possible to generate an absolute path to the desired module.

The following adjustment addresses the problematic loadChildren line:

loadChildren: () => import(new URL(entry.exposedModule, import.meta.url).toString()).then((m) => m[entry.ngModuleName])

By making use of

new URL(entry.exposedModule, import.meta.url)
, an absolute URL to the module is crafted based on the current module's URL and the specified relative path in entry.exposedModule.

This modification ensures that the module path is resolved accurately, enabling the dynamic importation of modules within the Lazy Loading setup. I hope this proves beneficial for your needs ;)

Answer №2

When you include a module using the syntax

import( '../requests/requests.module')
, it will be automatically compiled by your scaffolding tool (whether webpack or another).

However, if you dynamically import a module using import(entry.exposedModule), it will not be compiled automatically. You'll need to compile it independently and provide a URL for loading.

You can create a map that lists all the necessary modules or utilize module federation, which is an efficient approach to achieve this.

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

Type of JavaScript map object

While exploring TypeScript Corday, I came across the following declaration: books : { [isbn:string]:Book}={}; My interpretation is that this could be defining a map (or dictionary) data type that stores key-value pairs of an ISBN number and its correspon ...

Using Typescript with NodeJs

As I work on my app.ts file, I prefer using this approach. However, I’ve been encountering some problems with .d.ts imports, which are preventing me from accessing the full API of express. The main issue is that in Webstorm2016 (I haven’t tested it on ...

Indicating that jQuery is not recognized despite the jQuery file being successfully loaded

Currently, I am working on an angular.js application where I have included the jQuery file. However, despite this inclusion, I am encountering an error message. Error Uncaught ReferenceError: jQuery is not defined(anonymous function) @ popup.js:1 File ...

The audio stops when the ngaudio screen is clicked

When it comes to playing audio using the ngAudio service in AngularJS 1, the following code snippet is commonly used: $scope.audio = ngAudio.load("abc.wav"); $scope.audio.play(); However, some users have reported that after the sound is played, clicking ...

JS The clipboardData in ClipboardEvent is perpetually void

I am trying to retrieve files using CTRL+V from the ClipboardEvent in Angular6, but I am encountering an issue where the clipboardData is always empty regardless of whether I test images or text. This problem persists even when tested on the latest release ...

How can I dynamically set columns in an angular Google chart?

My data incoming consists of a dynamic series of information, for example: Date: Error Type: Count: 01/01 E1 10 01/01 E2 15 01/02 E1 12 01/02 E3 20 I am looking to create a chart that showcases Date ...

Querying with Node SQLite fails to return a value

So, here's my little dilemma: I have 3 methods that need to access a database file (SQLite3). export function F_SetupDatabase(_logger: any): void export function Q_RunQuery(query: string, db: "session" | "global"): any export func ...

Updating Parent Scope Value in AngularJS Custom Directive

As a newcomer to AngularJS, I am eager to create my own custom directive that will display notifications or alerts on the web page. For example, when a user successfully updates their information, I want a brief message to appear saying "Your information h ...

Tips for displaying dependent dropdown options in AngularJS

I need assistance with creating a form that includes two select boxes. Depending on the option selected in one select box, specific options should be shown or hidden in the other select box. For example: Select box A Options: Apple Banana Select Box B O ...

Angular filter is designed to search for elements that contain a specific value, rather than only those that are an exact match

I am currently trying to relate rules to fields using the 'filter' filter in Angular. You can see an example of this implementation here: http://plnkr.co/edit/dQiv5lRzhQNjXZ6pVdWO?p=preview The code I am using for this purpose is as follows: &l ...

"Exploring the world of AngularJS routing and using htaccess for rewriting URLs

How can I seamlessly integrate AngularJS ngRoute and htaccess rewrite? Currently, my ngRoute setup generates URLs like this: http://domain.com/#/something/somestring However, I would prefer cleaner URLs like: http://domain.com/something/somestring In ...

Hold off on showing the image until it has finished loading

// Here's the code snippet angular .module('imgapp', []) .controller('mainCtrl', mainCtrl); function mainCtrl() { var vm = this; vm.first = { title: 'Image 1', url: 'http://www.image-mapper.com ...

Assign the value of one variable to another variable using the same keys

I'm facing a scenario where I have two arrays named array1 and array2. My goal is to transfer the values from array2 into array1 for the properties that exist in array1, while keeping the default values for any properties that are not present. One ap ...

Adding Parameters to an Angular Service

I am facing a challenge that I can't seem to solve (I apologize for the multitude of questions, but Angular is really challenging me). Here is my Controller: friendsApp.controller('friendsController', ['$scope','friendsFacto ...

Continue iterating only when all promises have been resolved

My AngularJS requirement involves the following: for (var i = 0, len = self.Scope.data.length; i < len; i++) { var data = self.Scope.data[i]; var self = this; //Executing First asynchronous function self.EcritureService.createNewDa ...

The Angular factory function will only return a singular object instead of an array of objects

As a newcomer to Angular, I am currently working on loading a CSV list within a factory and then converting it to JSON. Utilizing Papaparse, a library for CSV to JSON conversion, inside the factory has allowed me to successfully obtain an array of objects ...

Creating a module within a component in angular - step by step guide

I am interested in dynamically creating a component inside another component. This will allow me to pass my dynamic HTML template directly to the decorator like this: //code /** * @param template is the HTML template * @param container is @ViewChild(& ...

Typescript mistakenly infers the wrong type: TS2339 error - it says that property 'selected' is not found on type 'string'

When examining the code snippet below, Typescript initially infers a type string for the inner element type of the values array. However, it subsequently raises an error indicating that string does not have the property "selected". let item = { values: [{ ...

Tips for utilizing chodorowicz / ts-debounce effectively

Looking to utilize the debounce function provided by the ts-debounce package (available at here) in my typescript project. However, struggling to find a concrete example of its usage in typescript. Would greatly appreciate any help or guidance on this ma ...

Symfony is unable to access uploaded files from an AngularJS interface

For the past 3 days, I've been grappling with uploading files via AJAX to my Symfony2 application using AngularJS. I'm utilizing my Symfony app as an API to deliver data to my Angular front end. While I can successfully post text and other data, ...