zee
zee

Reputation: 445

Lazy loading a module hangs the angular web app

I am sure I am missing something really simple, but I've spent hours on it and I can't figure it out.

In my app-routing.module, I am lazy loading modules (Angular 8):

{
    path: "console",
    component: LayoutComponent,
    canActivate: [AngularFireAuthGuard, ConsoleGuard],
    data: { authGuardPipe: redirectUnauthorizedToLogin },
    children: [
      {
        path: "",
        loadChildren: () => import("./dashboard/dashboard.module").then(mod => mod.DashboardModule),
        pathMatch: "full"
      },
      {
        path: "apps/inbox",
        loadChildren: () => import("./pages/apps/inbox/inbox.module").then(mod => mod.InboxModule),
      },
      {
        path: "contacts",
        loadChildren: () => import("../app/contacts/contacts.module").then(mod => mod.ContactsModule)
      },
    ]
  },

Everything works.

Now I want to add a new module. So I add this :-

{
  path: "campaigns",
  loadChildren: () =>
    import ("../app/campaigns/new-campaign/new-campaign.module").then(mod => mod.NewCampaignModule)
},

NewCampaign is basically empty :-

// new-campaign.module.ts

import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { NewCampaignComponent } from './new-campaign.component';

@NgModule({
  imports: [
    CommonModule,
  ],
  declarations: [NewCampaignComponent],
  exports: [NewCampaignComponent]
})
export class NewCampaignModule {
}

// new-campaign.component.ts

import { Component, OnInit } from "@angular/core";

@Component({
  selector: "common-new-campaign",
  templateUrl: "./new-campaign.component.html",
  styleUrls: ["./new-campaign.component.scss"],
})
export class NewCampaignComponent implements OnInit {
  constructor() {}

  ngOnInit() {}
}

<!-- new-campaign.component.html -->
<p>
  New Campaign
</p>

This basically hangs the app (I think it's in an infinite loop), but there's nothing in the console. No error. After a while Chrome says the application is not responding and I have to kill it.

I've done this a dozen times before (for this very app) and it just works. I can't figure out what I screwed up. Any hint will be greatly appreciated.

Upvotes: 1

Views: 1619

Answers (1)

Andrei Gătej
Andrei Gătej

Reputation: 11924

You also need to define the routes for any lazy loaded module.

You can follow the example from the docs.

Referring to your problem, I think this would solve your problem:

// new-campaign.module.ts

/* ... */

import { Routes, RouterModule } from '@angular/router';

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

/* ... */

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild(routes)
  ],
  declarations: [NewCampaignComponent],
  exports: [NewCampaignComponent]
})
export class NewCampaignModule {
}

Upvotes: 2

Related Questions