BeetleJuice
BeetleJuice

Reputation: 40916

Angular 4/5 route config broken

I have a root AppModule with the following routes (imported from an AppRoutingModule):

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

The AppComponent has a <router-outlet>. The HomeModule has the following routes (imported from a HomeRoutingModule):

const routes:Routes = [
  {
    path:'',
    component: HomeRootComponent,
    children: [
      {
        path:'',
        component: DashboardComponent
      }
    ]
  }
];

The HomeRootComponent has a <router-outlet>.

When I navigate to the empty route, the router correctly redirects to the /home route and the HomeModule is instantiated (I log from the constructor). I expected the dashboard to be displayed within the HomeRootComponent outlet, itself within the AppComponent outlet. However, neither the HomeRootComponent, nor the DashboardComponent gets instantiated. There is no error in the console.

Here is a live demo

Upvotes: 0

Views: 364

Answers (1)

LLai
LLai

Reputation: 13416

The issue is caused by circular dependencies. When I recreated the repo on my machine, I got some warnings

src/app/home/home-routing.module.ts -> src/app/home/index.ts -> src/app/home/home-routing.module.ts
src/app/home/home.module.ts -> src/app/home/home-routing.module.ts -> src/app/home/index.ts -> src/app/home/home.module.ts
src/app/home/index.ts -> src/app/home/home-routing.module.ts -> src/app/home/index.ts

So basically, the routing module is importing the barrel which is importing the routing module.

If you want to still use a barrel for the components, I would remove the modules from the barrel and import the modules directly as needed.

// app/home/index.ts
export * from './home-root.component';
export * from './dashboard/dashboard.component';

Importing the home-routing module directly

// app/home/home.module.ts
import {HomeRoutingModule} from './home-routing.module';
import {DashboardComponent, HomeRootComponent} from './';

Here is the working stackblitz (https://stackblitz.com/edit/pfx-ng-zkcy7h-4q5vvf?file=app%2Fapp-routing.module.ts)

Upvotes: 1

Related Questions