Issue encountered: Unable to access the property 'loadChildren' as it is undefined, while attempting to configure the path

How can I conditionally load the route path? I've attempted the code below, but it's throwing an error. Can someone guide me on how to accomplish this task?

[ng] ERROR in Cannot read property 'loadChildren' of undefined [ng] i 「wdm」: Failed to compile.

Also:

app-routing.module.ts:21 Uncaught TypeError: Cannot read property 'getLandingPage' of undefined at Module../src/app/app-routing.module.ts (app-routing.module.ts:21) at webpack_require (bootstrap:83) at Module../src/app/app.module.ts (app.component.ts:21) at webpack_require (bootstrap:83) at Module../src/main.ts (main.ts:1) at webpack_require (bootstrap:83) at Object.0 (main.ts:13) at webpack_require (bootstrap:83) at checkDeferredModules (bootstrap:45) at Array.webpackJsonpCallback [as push] (bootstrap:32)

app.routing.module.ts

const routes: Routes = [
  {
    path: "",
    redirectTo: this.getLandingPage(), // here is the issue
    pathMatch: "full",
  },
  {
   path: "tabs",
   loadChildren: "./pages/tabs/tabs.module#TabsPageModule",
  },
  {
   path: 'landing',
  loadChildren: './pages/landing/landing.module#LandingPageModule'
 },
];

export class AppRoutingModule {

  getLandingPage(): string {
    let url = "";
    switch (environment.hotelName) {
      case "h1":
        url = "tabs";
        break;
      case "h2":
        url = "landing";
        break;
      default:
    }
    return url;
  }


}

I have auth.gurad.ts as shown below. I don't think where I can use it for this.

export class AuthGuard implements CanActivate {
  constructor(private router: Router,
    private user: UserService,
    private localStorageService: LocalStorageService) { }
  canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
    return new Promise(async resolve => {
      const userInfo: UserInfo = await this.localStorageService.get(LocalStorage.USER_INFO);
      if (userInfo && (moment() < moment(userInfo.expireDate))) {
        this.user.guest = false;
        return resolve(true);
      }
      this.user.guest = true;
      this.router.navigate(["/sign-in"]);
      return resolve(false);
    });
  }
}

Answer №1

A common issue that many people encounter is rogue commas in their code. To fix this issue, make sure to remove the unnecessary comma at the end of your route list. The router interprets this extra comma as a fourth item in the list, which leads to a void 0 or undefined item without the necessary loadChildren property.

const routes: Routes = [
  {
    path: "",
    redirectTo: getLandingPage(),
    pathMatch: "full",
  },
  {
    path: "tabs",
    loadChildren: "./pages/tabs/tabs.module#TabsPageModule",
  },
  {
    path: 'landing',
    loadChildren: './pages/landing/landing.module#LandingPageModule'
  }
];

(be mindful of the missing comma after the 'landing' route entry)

Answer №2

Ensure your router config does not contain programmatic logic

This issue may arise if your router configuration uses anything other than a simple object with string keys and string values.


For instance, I encountered this problem when trying to set a regular expression in the data object of a specific route:

{
  path: 'path', 
  component: MyComponent,
  data: {
    regEx: /^[a-f\d]{24}$/i,
  },
},

The compiler threw an error with a vague message:

ERROR in Cannot read property 'loadChildren' of undefined


I came across similar examples where others faced this issue, like in this GitHub thread where someone used a constant as a key for a resolver:

const SOME_CONSTANT = 'someResolver',

{
  path: 'path',
  component: MyComponent,
  resolve: {
    [SOME_CONSTANT]: SomeResolver, // <-- you can't do this
  },
},

In essence, make sure to avoid defining keys, values, or any other parts of your router configuration programmatically to prevent encountering this issue.

Answer №3

Utilizing Route Guards can simplify your code by implementing a guard in the full match and handling redirects from there. Use conditionals as necessary.

For instance:

const routes: Routes = [
  {
    path: "",
    canActivate: [RouteGuard]
 },
  {
   path: "tabs",
   loadChildren: "./pages/tabs/tabs.module#TabsPageModule",
  },
  {
   path: 'landing',
  loadChildren: './pages/landing/landing.module#LandingPageModule'
 },
];

RouteGuard:

 canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
    return new Promise(async resolve => {
        this.router.navigate([environment.hotelName]);
        resolve(true)
  }
}

Answer №4

It is recommended to define the function getLandingPage() outside of the AppRoutingModule:

const getLandingPage = (): string => {
    let url = "";
    switch (hotelName) {
      case "h1":
        url = "tabs";
        break;
      case "h2":
        url = "landing";
        break;
      default:
    }
    return url;
  };

const routes: Routes = [
  {
    path: "",
    redirectTo: getLandingPage(),
    pathMatch: "full",
  },
  {
    path: "tabs",
    loadChildren: "./pages/tabs/tabs.module#TabsPageModule",
  },
  {
    path: 'landing',
    loadChildren: './pages/landing/landing.module#LandingPageModule'
  },
];

For a Stackblitz example, visit (https://stackblitz.com/edit/angular6-lazy-loading-hroo3l?file=src%2Fapp%2Fapp-routing.module.ts). It uses const hotelName instead of an environment variable due to the absence of environment variables in Stackblitz.

It is also uncertain how well this approach will work with Ahead-Of-Time compilation (AOT).

Answer №5

Encountered the same issue today 'ERROR in Cannot read property 'loadChildren' of undefined'.

It seems like this error can come up in various scenarios. In my case, it turned out to be a simple oversight - I forgot to add an 'export' keyword to a CanActivate class.

Here's how it was:

@Injectable({providedIn: 'root'})
class MyActivator implements CanActivate

What it should have been:

@Injectable({providedIn: 'root'})
export class MyActivator implements CanActivate

Tracking down this error took some time, so I wanted to share it here for others facing the same issue!

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

Tips for effectively navigating with the `Next-intl` and `next/link` componentsWhen working with the

I have implemented a next-intl library to enable multi-language support on my website. This means that the paths for different languages look like www.next.com/de or www.next.com/en Currently, I am utilizing NextJS 14. <NextLink href="/support-us& ...

The ng lint command is successful, yet an error appears in VS Code

I'm currently utilizing the tslint tool in my Angular project. Here is an excerpt from my tsconfig.json file: { "compileOnSave": false, "compilerOptions": { "downlevelIteration": true, "impor ...

Encountering an error when trying to serve a project after converting it from Angular to Ionic-Angular

I attempted to convert my angular project into a mobile app using Ionic Angular by replacing the src folder in Ionic with the one from my existing angular project. However, when I run the command: ionic serve, I encounter the following error: ionic serve ...

What is the best way to import a data type from another file into a `.d.ts` file without converting it into a module?

Recently encountered a peculiar scenario involving d.ts files and namespaces. I have some d.ts files where I define and merge a namespace called PROJECT. Take a look at how it's declared and automatically merged (across multiple files) below: file1 ...

Enabling non-declarative namespaces in React using Typescript: A beginner's guide

I'm diving into the React environment integrated with Typescript, but I still have some confusion about its inner workings. I really hope to receive thorough answers that don't skip any important details. I came across a solution that involves d ...

Step-by-Step Guide: Customize the Background Color in an Angular 4 Select Dropdown Based on the Selected Option

I'm facing a challenge in setting the background color of a select element based on the color attribute of its currently selected option. I'm using Angular 4 for this task. An example of what I am attempting to accomplish is shown below: <se ...

Encountering a 404 error when importing http/server in deno

The file named index.ts is located below import { serve } from "https://deno.land/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b0c3c4d4f0809e8186869e80">[email protected]</a>/http/server.ts"; function ...

How can I utilize the Redux store outside of a component in a React application with ASP.NET Core and TypeScript?

While I have some experience with React, I am new to using Redux. Luckily, Visual Studio 2017 comes with a built-in template for React + Redux under .NET Core 2.0. About my environment: Visual Studio 2017 React 15.6.1 TypeScript 2.4.1 Redux 3.7.1 Rea ...

Incorporating optional fields into the form builder without being mandatory

For my current project on Ionic 4, I have implemented a form builder to create and validate forms. I have also included the [disabled] attribute in the form to disable it if all fields are not valid. However, I noticed that even if I do not add Validators ...

Incorporate all photographs from a designated directory in the gallery into an Angular 6 PWA Application

Currently, I am developing a Progressive Web Application that requires me to showcase all images stored under a specific directory (for instance, all pictures saved in the "Downloads" folder on a mobile device) within a personalized grid view. I would lik ...

Keeping track of the authentication state in AngularFire2 on page reload to verify if the user is logged

I am facing a challenge in my angular4 app that uses angularfire2. I need to determine if a user is logged in when the page loads. Logging in and out works fine, and I have set up a guard on the router to handle unauthorized access. In one example I came ...

Passing a class as a parameter in Typescript functions

When working with Angular 2 testing utilities, I usually follow this process: fixture = TestBed.createComponent(EditableValueComponent); The EditableValueComponent is just a standard component class that I use. I am curious about the inner workings: st ...

Angular 8 is facing an issue where classes defined dynamically in the 'host' property of a directive are not being properly applied to the parent template

In my Angular 8 application, I am working on implementing sorting using the ng-bootstrap table. I referred to the example available at . In the sample, when I hover over the table header, it changes to a hand pointer with a highlighted class applied as sho ...

Changing the text color of mat-chips in Angular Material

Having a mat-chip-set and multiple mat-chip elements with a custom product-chip class: <mat-chip-set> <mat-chip class="product-chip" *ngFor="let category of categories"> {{category}} </mat-chip> </mat-chip-s ...

The art of connecting with Angular 2 router and Components

Here are the elements I have: <app-scrollable-area (scrolledDown)="..." class="scrollable-y"> <router-outlet></router-outlet> </app-scrollable-area> I'm wondering how to communicate this event (scrolledDown) to inside ...

Tips for utilizing multiple components in Angular 2

I am a beginner in angular2 and I am attempting to utilize two components on a single page, but I keep encountering a 404 error. Here are my two .ts files: app.ts import {Component, View, bootstrap} from 'angular2/angular2'; import {events} f ...

Typescript's date function offers a variety of useful features

Can anyone help me create a function that formats a date string for sorting in a table? The date is in the format: 08.04.2022 16.54 I need to convert this to a number or date format that can be sorted. I'm new to TypeScript and could use some guida ...

What is the best way to incorporate the C# in keyword into TypeScript?

When coding in C#, I often utilize the in keyword within conditional statements. if (1.In(1, 2) I am curious about how to implement the IN keyword in typescript. ...

The challenge of migrating from Angular2 Rc4 to Rc5: dealing with traceur bug

Encountering 'traceur 404' error in console during the migration process of my angular cli project from Rc4 to Rc5 https://i.stack.imgur.com/j4SU1.png Referenced this article for guidance: app.module.ts import {NgModule} from '@angu ...

What is the best way to transform this Ajax query into an HTTP client request in Angular 8?

I have an ajax request that looks like this: var data = { REQUEST: 'GetFeatureInfo', SERVICE: 'WMS', VERSION: '1.1.1', LAYERS: layerName, STYLES: '', FORMAT: 'image/png', INFO ...