Lazy loading in Angular 2 hits a snag when using a module that is shared

After successfully lazy loading my AccountModule, I encountered an issue when adding my SharedModule to it. All of my eagerly loaded modules seemed to be forgotten and I started receiving the following error:

The component FoodComponent is not part of any NgModule or the module has not been imported into your module.

The FoodComponent was originally being loaded and rendered correctly until I introduced the AccountModule with lazy loading. Removing this component from the app led to the same issue with the next eagerly loaded component. What is causing this behavior with my SharedModule?

shared.module.ts

// ... imports ...

@NgModule({
  imports: [
    CommonModule,
    MaterialModule.forRoot(),
    ReactiveFormsModule,
    AppRoutingModule
  ],
  declarations: [     
    CalNavComponent, 
    IngredientsListComponent, 
  ],
  exports: [ 
    MaterialModule, 
    ReactiveFormsModule, 
    CommonModule, 
    AppRoutingModule,

    CalNavComponent, 
    IngredientsListComponent, 
  ],
  providers: [ 
    UserDataService 
  ],
})
export class SharedModule { }

account.module.ts

// ... imports ...

const routerConfig: Routes = [{
  path: '',
  component: AccountComponent
}]

@NgModule({
  imports: [
    SharedModule, /* Works fine when this is gone */
    RouterModule.forChild(routerConfig)
  ],
  declarations: [ 
    AccountComponent
  ],
  exports:[
    AccountComponent
  ]
})
export class AccountModule { } // adding 'default' results in "cannot find module at app/features/account/account.module"

app-routing.module.ts

const routes: Routes = [
  {
    path: '',
    redirectTo: 'food', 
    pathMatch: 'full'
  },
  { 
    path: 'account',
    loadChildren: 'app/features/account/account.module#AccountModule'
    // component: AccountComponent, /* This worked fine*/
  },
  {
    path: 'food',
    component: FoodComponent
  },
  //... more paths
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})

export class AppRoutingModule {
  constructor() { }
}

Answer №1

It turns out that I was following an outdated tutorial for AppRoutingModule. Instead of using a regular NgModule module, I made the switch to a ModuleWithProviders module.

account.routing.ts

import { AccountComponent } from './account.component';
import { ModuleWithProviders } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

const routes: Routes = [{
  path: '',
  component: AccountComponent
}]

export const AccountRouting: ModuleWithProviders = RouterModule.forChild(routes)

account.module.ts

import { AccountRouting } from './account.routing';
import { NgModule } from '@angular/core';
import { SharedModule } from '../shared/shared.module';
import { AccountComponent } from '../account/account.component';

@NgModule({
  imports: [
    SharedModule,
    AccountRouting
  ],
  declarations: [ 
    AccountComponent
  ],
  exports:[
    AccountComponent
  ]
})
export class AccountModule { }

app.routing.ts

import { FoodComponent } from './features/food/food.component';
// import { AccountComponent } from './features/account/account.component';
import { ModuleWithProviders } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';


const routes: Routes = [
  {
    path: '',
    redirectTo: 'calendar',
    pathMatch: 'full'
  },
  { 
    path: 'account',
    loadChildren: 'app/features/account/account.module#AccountModule'
    //component: AccountComponent,
  },
  {
    path: 'food',
    component: FoodComponent
  },
  //... more routes
];

export const routing: ModuleWithProviders = RouterModule.forRoot(routes)

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

Fixing Error 415 when Sending Angular Posts to Asp.Net Web Api on IIS

I'm having a difficult time figuring out how to make a simple Web Api call work, and I'm feeling quite frustrated because it's much more complicated than anticipated. I have created a basic Web Api (for testing purposes) that is being consu ...

How to successfully utilize TypeScript ES6 modules and RequireJS for registering Angular elements

I am in the process of updating a current Angular application that uses AMD with TypeScript 1.5 ES6 module syntax. Our modules are currently stored in separate files, and the main "app" module is defined like this... define('app', ['angular ...

Enhance the aesthetic appeal of the imported React component with added style

I need assistance with applying different styles to an imported 'notification' component within my header component. The notification component has its own CSS style, but I want to display it in the header component with unique styling. How can I ...

Chromium browser experiencing issues with the functionality of Dropdown component

My issue involves a basic pie chart with a dropdown menu (created with the <select> tag) that allows users to change the data displayed on the chart. I have implemented this in Angular 6 and it works perfectly fine in Firefox. However, when I tested ...

Tips for successfully sending an interface to a generic function

Is there a way to pass an interface as a type to a generic function? I anticipate that the generic function will be expanded in the future. Perhaps the current code is not suitable for my problem? This piece of code is being duplicated across multiple fil ...

What is the purpose of decorators in Angular 2?

As a newcomer to Angular 2, I've noticed that certain properties like selector and template are included in components decorators rather than in components classes. Can anyone explain the reasoning behind this design choice? I'm curious about th ...

Displaying Modal from a separate component

CardComponent: export class Card extends Component<Prop, State> { state = { isCancelModalOpen: false, }; marketService = new MarketService(); deleteMarket = () => { this.marketService .deleteMar( ...

"Error occurs as a result of an unspecified attribute in the map

Hello, I am currently traversing a tree structure recursively. To handle undefined nodes in the tree, I have implemented guards to prevent any failures. However, during the mapping of children nodes, I encountered the following error: Error Output Adri ...

Angular's table data display feature is unfortunately lacking

Below is a simple HTML code snippet: <div class="dialogs"> <div id="wrapper" > <p>{{createTestingConstant()}}</p> <ng-container *ngFor="let one of contacts"> <p>{{one ...

Angular2 checkboxes for filtering data

I'm working with an Angular2 grid that showcases an array of Fabrics, each with its own color or fabric type properties. Right now, all Fabrics are displayed in the grid, but I need to implement a series of checkboxes for color and fabric type, along ...

Inside the function() in angular 2, the value of 'this' is not defined

I've integrated a UIkit confirmation modal into my app. However, I'm encountering an issue when trying to click the <button> for confirmation. The this inside the function is showing up as undefined. Here's the snippet of code in quest ...

Testing a React component that uses useParams: A step-by-step guide

I've been working on creating a BBS App using TypeScript, React, React Router, and React Testing Library. However, I've encountered an issue where a component utilizing useParams is not passing a test. Interestingly, it seems to be working correc ...

establish the data type for the key values when using Object.entries in TypeScript

Task Description: I have a set of different areas that need to undergo processing based on their type using the function areaProcessor. Specifically, only areas classified as 'toCreate' or 'toRemove' should be processed. type AreaType ...

Why is Firebase Deploy only detecting 1-2 files? It might be due to the default index of Firebase hosting

I'm currently in the process of deploying my Angular App to Firebase Hosting. However, I am encountering an issue where it only displays the default firebase index hosting with no changes. To set up the deployment, I have used firebase init and speci ...

Associate a template reference variable with an attribute directive category

Currently, I am in the process of creating an attribute directive that will receive multiple templates containing additional data for filtering. This extra information will be utilized later to select the appropriate template. To achieve this, I have exten ...

What sets TypeScript apart from AtScript?

From what I understand, TypeScript was created by Microsoft and is used to dynamically generate JavaScript. I'm curious about the distinctions between TypeScript and AtScript. Which one would be more beneficial for a JavaScript developer to learn? ...

Discover how to capture and process POST form data in Angular originated from external sources

I am currently building a website that utilizes Java for the backend and Angular for the frontend. I have encountered a scenario where external websites may transmit data to my site via POST form submissions. For example, ▼ General    & ...

Error in TypeScript on SendGrid API: Invalid HttpMethod

Here is my code snippet: import sendgridClient from '@sendgrid/client' sendgridClient.setApiKey(process.env.SENDGRID_API_KEY); const sendgridRequest = { method: 'PUT', url: '/v3/marketing/contacts', bo ...

Express server experiencing issues with generating Swagger documentation

I've been working on an Express API and decided to implement documentation using Swagger and JSDoc. However, the documentation is not working as expected. Here's how I've set it up: docs.ts: import swaggerJSDoc, { Options } from "swagg ...

Angular Material Dropdown with Multi-Column Support

I'm working on customizing the selection panel layout to display items in multiple columns. However, I'm facing an issue where the last item in each column appears off-center and split, causing overflow into the next column instead of a vertical ...