Chrillewoodz
Chrillewoodz

Reputation: 28328

Angular 2 AOT and lazy loading sub modules

Before I upgraded to angular-cli.beta-24 I had this route structure:

+route1
 - +subroute1
 - +subroute2
 - +subroute3

But this fails when having the subroutes defined in the router.module of +route1 because they can't be found now that AOT is enabled by default.

I can get it working by not having the subroutes defined there, and instead moving them to the same router.module as all the other routes in the app. Instead looking like this:

+route1
+subroute1
+subroute2
+subroute3

With the routes obviously not being subroutes anymore.

While this works, it's not a viable solution for me since my breadcrumbs relies on the router tree and it just creates a mess overall if you can't have a router tree anymore.

Here's an example (route1's router.module file):

const routes: Routes = [
  {
    path: '',
    component: Route1Component
  },
  {
    path: 'subroute1',
    loadChildren: '+subroute1/subroute1.module#Subroute1Module'
  },
  {
    path: 'subroute2',
    loadChildren: '+subroute2/subroute2.module#Subroute2Module'
  },
  {
    path: 'subroute3',
    loadChildren: '+subroute3/subroute3.module#Subroute3Module'
  }
];

Why can't you define routes like this when using AOT? What am I missing?

Upvotes: 0

Views: 974

Answers (1)

maxime1992
maxime1992

Reputation: 23793

AOT and lazy loading works well together since BETA.21 (I made a post about that).

Instead of passing to loadChildren a relative path from . you should start from the app folder like that :

const routes: Routes = [
  {
    path: '',
    component: Route1Component
  },
  {
    path: 'subroute1',
    loadChildren: 'app/+route1/+subroute1/subroute1.module#Subroute1Module'
  },
  {
    path: 'subroute2',
    loadChildren: 'app/+route1/+subroute2/subroute2.module#Subroute2Module'
  },
  {
    path: 'subroute3',
    loadChildren: 'app/+route1/+subroute3/subroute3.module#Subroute3Module'
  }
];

EDIT 1 : It could come from your barrel.

There was some trouble with beta.23 and they did jump to beta.24. BUT a breaking change was introduced in beta.23 and if you read only the changelog for beta.24 you might have missed it. Please take a look to Beta 23 changelog, breaking changes :

blueprints: The app root module and component must now be imported directly. (e.g., use import { AppModule } from './app/app.module'; instead of import { AppModule } from './app/';)

If I understood well, barrels are not working with AOT (which is now enabled by default). Basically, you can remove index.ts and should import what you need directly.

Upvotes: 2

Related Questions