McGuireV10
McGuireV10

Reputation: 9926

Angular2 RC5 router can't find module (lazy load)

I have a pretty simple Angular2 RC5 test project which attempts to use routing to lazy load modules. I can't see what's wrong with the project.

Folders

app
  |-about (contains about.module.ts and about.component.ts)
  |-home (contains home.module.ts, home.component.ts)

app.routing.ts

export const routes: Routes = [
    { path: '', redirectTo: 'home', pathMatch: 'full' },
    { path: 'home', loadChildren: './app/home/home.module' },
    { path: 'about', loadChildren: './app/about/about.module' }
];

export const routing = RouterModule.forRoot(routes);

home.module.ts

import { NgModule }         from '@angular/core';
import { HomeComponent }    from './home.component';

@NgModule({
    declarations: [HomeComponent],
    exports: [HomeComponent]
})

export default class HomeModule { }

home.component.ts

import { Component }        from '@angular/core';

@Component({
    template: `<h2>Home...</h2>`
})

export class HomeComponent { }

I know the redirect to "home" is working, at startup I can see that home.module.js and home.component.js files are downloaded, but then it throws a console error message Cannot find 'HomeModule' in './app/home/home.module' (and in the network traffic tab I can confirm that both of the js files are correct, spelling is correct, etc.)

Upvotes: 1

Views: 2555

Answers (1)

Kamil Myśliwiec
Kamil Myśliwiec

Reputation: 9168

Just replace:

{ path: 'home', loadChildren: './app/home/home.module#HomeModule' },

Into this line:

{ path: 'home', loadChildren: './app/home/home.module' },

If you already add export default in your module file, you do not have to specify name in path.

Of course, if you forgot about "default", the only way to select proper module is to add #name attribute - this is the second way. You could use one of them, not both.

And also in your HomeModule, add:

imports: [ 
    RouterModule.forChil‌​d([ 
       { path: '', component: HomeComponent } 
    ]) 
], 

Because all modules could have few components (not only one) so it is necessary to show angular a path to your main component.

Upvotes: 2

Related Questions