How can I incorporate the compiled Angular file dynamically into my routing system?

The database stores the URL that should load the module from the 'dist' directory.

{
  "personal-area": "js/compile-module.js",
  "product": "js/compile-module2.js"
}

For example, when using the application:

http://localhost:8282/#/personal-area

The application then lazy loads the module from:

http://localhost:8282/js/compile-module.js

The modules are precompiled in advance and are not involved during the main application building stage, which means there are no paths to the sources of Angular modules.

In the routing file (app.routers.ts), the component handler stores the server path to the module file based on the URL pulled from the database.

export const ROUTES: Routes = [

    {
        path: '**',
        component: WorkspaceOutletComponent
    },

];

In the main handler, there is a method trying to load the module dynamically for the application to function properly.

@Component({ ... })
export class WorkspaceOutletComponent {

    constructor() {
    }

    ngOnInit() {
        // detect routing and execute initialization
    }

    public init(workSpaceUrl: string, workSpacePathModule: string) {
        console.log(`url: ${workSpaceUrl} path: ${workSpacePathModule}`);

        this.router.resetConfig([
            {
                path: workSpaceUrl, loadChildren: workSpacePathModule
            }
        ]);

        this.router.navigate([workSpaceUrl])
            .then(() => console.log('Navigate to'))
            .catch((e) => console.error('Error', e));
    }

}

The application is built using webpack 2. However, when trying to replace routing, an error occurs indicating difficulty dynamically loading the required module from the database without source codes available.

If SystemJS is used, it also encounters issues while attempting to load the module from the disk instead of the source.

this.router.resetConfig([
            {
                path: workSpaceUrl, loadChildren: SystemJS.import(workSpacePathModule).then(function(m) {
                    console.log(m);
                })
            }
        ]);

More information about how module loading works can be found at: https://github.com/angular/angular-cli/issues/4234#issuecomment-275345763

Could it be that Angular requires an exact name to compile a hash map, thus causing issues in passing the necessary parameters if the source code is unavailable?

Answer №1

Uncertain about the effectiveness of using the reset route method, but it is essential to generate lazy routes for all potential modules you plan to utilize.

The value assigned to loadChildren must be a static string. Dynamically calling a function within this parameter is not allowed and could disrupt the Angular CLI's collaboration with Webpack in producing lazy routes.

It is advisable to generate all possible lazy routes and then load only the specific one(s) needed at runtime. However, caution should be exercised as resetConfig has the ability to reset the entire configuration.

An alternative approach is utilizing linkNgModuleFactory to acquire a module factory instance (which Angular generates from a module after compiling either in-browser or AoT), potentially for use with NgComponentOutlet.

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 could be causing this TypeScript code to not pass typechecking?

defining two objects in TypeScript with different property sets and assigning them to each other. Link to more information ...

The property 'i' is not recognized on the type 'AppComponent'

Check out my code here; Take a look at my code here I attempted to implement a delete button to remove array objects using the ngFor directive ...

A one-to-many relationship does not include the insertion of the parent item

My database has a one to many relationship. When I perform a select operation, everything works correctly. However, when trying to insert data, the insertion occurs in the main table, but updates are triggered in other tables. Error Log from Console [0] ...

A schema already exists with the key or ID "http://json-schema.org/draft-06/schema"

While attempting to include the Material library in my Angular project using npm install --save @angular/material @angular/cdk, I encountered some issues as described in this question: Error TS2315: Type 'ElementRef' is not generic material angul ...

Transferring client-side data through server functions in Next.js version 14

I am working on a sample Next.js application that includes a form for submitting usernames to the server using server actions. In addition to the username, I also need to send the timestamp of the form submission. To achieve this, I set up a hidden input f ...

Converting objects to arrays in Typescript: A step-by-step guide

Can anyone assist me in converting a string to a Typescript array? Any help would be greatly appreciated. Take a look at the following code snippet: private validateEmptyOption(): any { console.log("CHECKED") let isValid = true; this.currentF ...

What is the best way to create a function that can securely search for a URL containing parameters while ensuring type safety?

I am working on a NextJS/React application. We have a large object containing internal URLs, each with a createPath function that looks similar to this: const URLS = { dashboard: { createPath: ({ accountNumber }: { accountNumber: string }) => ...

An issue has occurred in my deeply nested reactive form where I am unable to read the properties of null, specifically the 'controls' property

I have encountered an issue with a deeply nested form that communicates with a REST endpoint upon submission. While the first two levels of the form are functioning properly, I am facing numerous challenges when trying to work with the third level. One par ...

Angular Karma issued a WARNING about a 404 error during the test execution on the web server

I've been struggling to set up a foundation for implementing angular2, sass, and ng2-bootstrap. This particular project is derived from the angular2-seed project, and you can access the entire codebase here: https://github.com/omargon/angular-seed-sas ...

How can I customize the variables in Webpack for Sass and Foundation?

Currently, I am in the process of using webpack to manage all of my project assets. In my app.js file, I am loading and concatenating my assets with the help of ExtractTextPlugin: import 'foundation-sites/scss/normalize.scss'; import 'foun ...

Ensure the most recently expanded item appears at the top of the TreeView by updating to Mui version

I'm working on a feature where I want to scroll the expanded TreeItem to the top when it has children and is clicked on for expansion. Any suggestions on how to make this happen? ...

Verify the login details of a distant website using Angular

Currently, I am in the process of developing a user interface for Hacker News using Angular 7. Typically, I rely on public APIs for various functionalities, but unfortunately, login services are not accessible through these APIs. In order to address this ...

Limiting @Input Value to a Certain Number Range using Angular

I need to include an InputSignal in my Angular component that only accepts arrays of numbers. Each number in the array should fall between 0.01 and 10, and cannot have more than 2 decimal places. It is important to enforce these restrictions to ensure tha ...

Why is my ASP.NET Core Crud request failing with incorrect method matching?

I am facing an issue with the third method in my Angular ASP.NET Core Controller. The first two methods work fine, but the GetBookItemsByTitle does not seem to be firing correctly. As I am still learning, I believe my mistake here is obvious. /// <summ ...

The time format in IST returns an undefined value in JavaScript

console.log(Date.parse('Wed Jul 07 04:49:10 IST 2021')); // returns NAN console.log(Date.parse('Wed Jul 07 04:49:10 EDT 2021')); // working as intended Is there a way to convert the date string 'Wed Jul 07 04:49:10 IST 2021' ...

Adding an active class on a selected chat list item in Angular - here's how!

We are currently developing a chat component where users can click on the left side chat item to open messages with the selected user. We have implemented an active class that changes the color of the selected chat list item. Our goal is to apply the activ ...

Using Observable and EventEmitter to efficiently transfer data between parent and child components in Angular

I am struggling with the following structure: Main component (displays items using item-service) Panel component (includes search components) SearchByTitle component (with input field for title of items) SearchBySomething component (with input field ...

Component unit testing in Angular 2/4 fails to register click events causing a lack of change detection

I'm currently working on testing a component in Angular 2/4 to determine if clicking on a button element will result in the desired changes. However, I'm facing an issue with triggering the click event. Here is the component code: import { Comp ...

Encountered a React TypeScript issue stating that the type '{ ... }' cannot be assigned to the type 'IntrinsicAttributes & IntrinsicClassAttributes<...>'

Embarking on a new journey with a react typescript project, I encountered this puzzling error: Failed to compile. /Users/simon/Code/web/react-news-col/src/MainNewsFeed.tsx TypeScript error in /Users/simon/Code/web/react-news-col/src/MainNewsFeed.tsx(27,35 ...

Redis is prepared and awaiting authorization for authentication. ReplyError: NOAUTH Authentication needed

When attempting to connect to a Redis instance hosted on redislab, an error message is received indicating Redis ready ReplyError: NOAUTH Authentication required. const pubClient = createClient({ url: `${config.redisLabHost}:${config.redisLabPort}` }); pub ...