Upon deployment, Angular encounters issues with routing to lazy loaded modules

I recently completed development on a new Angular application that utilizes lazy loading for improved performance.

During local testing using ng serve (or ng serve --prod to mimic production mode), the app compiled without errors and functioned properly. I was able to navigate seamlessly between eager loaded modules and lazy loaded ones without encountering any issues.


THE ISSUE:

However, when I built the app for production using ng build --prod and deployed it on the server, I encountered a problem. I could not navigate from the default eager loaded module (the homepage) to a lazy loaded module.


ERROR STACK

The console displayed the following errors:

  1. Error:

    ERROR Error: Uncaught (in promise): Error: Cannot enable prod mode after platform setup. Error: Cannot enable prod mode after platform setup.

    This error occurred when… attempting to navigate to any lazy loaded module for the first time

  2. Error:

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

    This error occurred when… trying to navigate to a lazy loaded component again, after encountering the first error

An interesting observation is that these errors did not result in a 404 not found status, but rather seemed to be "normal" Angular errors.


MY CODE:

Project structure

app.module.ts (& app.routing.ts)
|__lazy.module.ts (& lazymodule.routing.ts)
|__admin.module.ts (& admin.routing.ts)

app.routing.ts

// ... imports …
const appRoutes: Routes = [
  {
    path: '',
    redirectTo: '/dashboard',
    pathMatch: 'full',
  },
  {
    path: 'dashboard',
    component: DashboardComponent,
    canActivate: [AuthGuard]
  },
  {
    path: 'lazy',     
    loadChildren: "./lazy/lazy.module#LazyModule",
    canLoad: [AuthGuard]
  },
  {
    path: 'admin',     
    loadChildren: "./admin/admin.module#AdminModule",
    canLoad: [AuthGuard]
  },
  { path: '**', redirectTo: '/dashboard', canActivate: [AuthGuard] }
];

export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes, { preloadingStrategy: SelectiveStrategy, useHash:true });

selective.strategy.ts

// ... imports ...
@Injectable()
export class SelectiveStrategy implements PreloadingStrategy {

    preload(route: Route, load: Function): Observable<any> {
        if (route.data && route.data['preload']) {
            return load();
        }
        return Observable.of(null);
    }
}

lazymodule.routing.ts

const routes: Routes = [
  { path: '', component: FooComponent, canActivate: [AuthGuard] },
  {
    path: 'foo',
    component: FooComponent,
    canActivate: [AuthGuard]
  },
  {
    path: 'new',
    component: NewElementComponent,
    canActivate: [AuthGuard]
  },
  { path: '**', redirectTo: '/dashboard', canActivate: [AuthGuard] }
];

export const routing: ModuleWithProviders = RouterModule.forChild(routes);

VERSIONS:

Server: Windows Server 2012 R2
IIS Version: 8.5.9600.16384
Angular/common Version: 6.1.5
Angular & Angular-CLI Versions: 6.1.4


MY ATTEMPTS TO FIX:

1) Successfully tested locally by executing ng build --prod.
2) Unable to resolve issue even when running locally with ng serve --prod.
3) Added useHash:true option in the RouterModule.forRoot of app.routing.ts, but no luck.
4) Moved the routing logic into the app.module.ts file, which also did not work.
5) Tried using a root relative path like

src/app/lazy/lazy.module#LazyModule
, still unsuccessful.
6) Attempted to deploy files generated by ng serve --prod on the server folder, but no success.
7) Updated all npm packages, but issue persisted.


What could be causing this problem? Is it related to the code implementation or perhaps an issue with the server configuration?

Let me know if you need more information or specific sections of the code.

Answer â„–1

A temporary solution has been discovered for the issue at hand. However, a permanent fix will need to be implemented by the angular team as it pertains to a problem with the production build aot and build-optimizer.

Currently, the workaround involves disabling aot and build-optimization. This can be done in one of two ways: either through the command line for a one-time effect:

ng build --prod --aot=false --build-optimizer=false

Or, for a lasting impact, update your production configurations in your angular.json file to include:

"configurations": {
        "production": {
          "optimization": true,
          "outputHashing": "all",
          "sourceMap": false,
          "extractCss": true,
          "namedChunks": false,
          "aot": false,
          "extractLicenses": true,
          "vendorChunk": false,
          "buildOptimizer": false,
          "fileReplacements": [
            {
              "replace": "src/environments/environment.ts",
              "with": "src/environments/environment.prod.ts"
            }
          ]
        }
      }

Make sure to set false for both aot and build-optimizer.

Answer â„–2

Utilize fat arrow functions for implementing lazy loading to eliminate concerns about module paths

Here's an illustrative example:

const appRoutes: Routes = [
  {
    path: '',
    redirectTo: '/dashboard',
    pathMatch: 'full',
  },
  {
    path: 'dashboard',
    component: DashboardComponent,
    canActivate: [AuthGuard]
  },
  {
    path: 'lazy',     
    loadChildren: () => LazyModule,
    canLoad: [AuthGuard]
  },
  {
    path: 'admin',     
    loadChildren: () => AdminModule,
    canLoad: [AuthGuard]
  },
  { path: '**', redirectTo: '/dashboard', canActivate: [AuthGuard] }
];

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

Utilizing Angular2 to scan barcodes

Im looking to create an application in asp.net 5 / Angular2 and I am encountering an issue with scanning barcodes. This is the TypeScript code for my component: @Component({ selector: 'barcode-scanner', templateUrl: 'app/scan.html& ...

Retrieving the return type of generic functions stored in a map

In this unique scenario, I have a dictionary with polymorphic functions that accept the same argument but return different results: const dict = { one: { foo<A>(a: A) { return [a] as const } }, two: { foo<A>(a: A) { ...

Developing a versatile Angular2 component that has the potential to be utilized across various sections of a website

Use Case: I need to display a processing screen during asynchronous calls to keep end users informed about ongoing activities across multiple sections of the website. To achieve this, I decided to create a reusable component at the global level. Issue: As ...

Error in Django framework: Attempting to insert a null value in the "hardware_type" column violates the not-null constraint

I have encountered a problem for which I have found solutions on Stack Overflow, but unfortunately, they do not work in my specific case. Here is a snippet of my code: models.py hardware_used = models.CharField(max_length=20, blank=True, null=True) core ...

Why won't my Angular app hit a breakpoint while debugging?

I'm relatively new to the world of Visual Studio Code and Angular applications with a C# Web API back-end. My issue lies in hitting breakpoints within my Angular app using VS Code, even though I can hit them without any problems in C#! Running both a ...

Angular setup prompting for anonymous usage statistics collection by the Angular development team

This is my first time installing Angular and I ran into confusion at this step. The terminal message prompted me with the option to share anonymous usage data with the Angular Team at Google under their Privacy Policy. Here's what it said: ? Would y ...

API endpoint generating a Vue component as a rendered output

In the process of developing a document templater service, I am faced with the challenge of handling numerous document templates (contracts, protocols, etc.) written in Vue. The concept revolves around clients sending props in the body, which are then pass ...

Mastering the art of styling with SASS

The introductory guide suggests: When it comes to integrating the Kendo UI theme into your project, there are numerous approaches available. One recommended method is utilizing Webpack along with its Sass loader, enabling the customization of the Kendo UI ...

What is the best way to send ServerSideProps to a different page in Next.js using TypeScript?

import type { NextPage } from 'next' import Head from 'next/head' import Feed from './components/Feed'; import News from './components/News'; import Link from 'next/link'; import axios from 'axios&apo ...

Script for running a React app with Prettier and eslint in a looping fashion

My Create React App seems to be stuck in a compile loop, constantly repeating the process. Not only is this behavior unwanted, but it's also quite distracting. The constant compiling occurs when running the default npm run start command. I suspect t ...

An argument of type 'Array<T>' necessitates the inclusion of one type argument

I've come across this issue multiple times on various online forums. Despite trying different solutions, I'm still unable to resolve the following error: (11,23): Generic type 'Array' requires 1 type argument(s). This pertains to t ...

Implementing computed properties: A guide to incorporating type setting

I currently have two separate interfaces defined for Person and Dog. interface Person { name: string; weight: number; } interface Dog { name: string; mass: number } const specificAttribute = isDog ? 'mass' : 'weight'; ...

The initial character of the input must always be a letter

I need assistance with an input element that requires 5 characters, with the first character being a letter: <input mdInput #acronyme placeholder="Company" type="text" maxlength="5" minlength="5" required [value]="acronyme.value.toUpperCase()"> Th ...

The compilation of the Angular application is successful, however, errors are arising stating that the property does not exist with the 'ng build --prod' command

When compiling the Angular app, it is successful but encountered errors in 'ng build --prod' ERROR in src\app\header\header.component.html(31,124): : Property 'searchText' does not exist on type 'HeaderComponent&apo ...

PlatypusTS: Embracing Inner Modules

Incorporating angular, I have the capability to fetch object instances or import modules using the $injector in this manner: export class BaseService { protected $http: angular.IHttpService; protected _injector: angular.auto.IInjec ...

Can you explain the distinction between using [ngFor] or [ngForOf] in Angular 2?

From what I gather, both serve the same purpose. However, ngFor operates similar to collections. ngForOf functions more like generics. Am I correct in my understanding? Or can you provide more insight on the differences between ngFor and ngFor ...

What is the best way to transmit two distinct sets of data from a child component to the v-model of a parent component?

Currently, I am working on a project using vuejs 2 and typescript. In this project, I need to pass two different sets of data - data and attachments - within the parent component. I am utilizing vue-property-decorator for this purpose. However, I am facing ...

Troubleshooting Ionic 4 application for unit testing errors

Attempting to write a basic unit test similar to this one: it('should create the app', async(() => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; expect(app).toBeTruthy ...

Utilizing nested services for enhanced functionality

I'm facing an issue with my folder structure: . ├── lib/ │ └── dma/ │ ├── modules/ │ │ └── cmts/ │ │ ├── cmts.module.ts │ │ └── cmts.service.ts │ └┠...

When the page is first loaded, the select options dropdown using NgFor and NgValue does not display the initial object from the list

I am facing an issue with a select options dropdown that contains a list of objects. I have used ngValue to set the value of the dropdown as an object. However, upon page load, the dropdown does not display the first object from the list; it only shows obj ...