1
votes

I'm new to Angular 2. I wanted to show 'HomeComponent' at root URL (http://localhost:4200) and 'PostsComponent' at http://localhost:4200/posts. I have set the following at app.routing.ts.

export const AppRoutes: Routes = [
  {
    path: '',
    component: AdminLayoutComponent,
    children: [{
      path: '',
      component: HomeComponent
    }, {
      path: 'posts',
      loadChildren: './posts/posts.module#PostsModule'
    },{
      path: '**',
      component: PageNotFoundComponent
    }]
  }
];

Home component is showing correctly first time. When I visit to posts URL ( post component also showing correctly ) and come back to root URL ( by clicking on a link - eg: Home link ) it is showing 'page not found component'. But when I reload the page it is showing home component correctly.

What am I missing here ?

NOTE: If I use "redirectTo" option for '' ( empty ) path, then it is working. Then home component will show at http://localhost:4200/home. But I want to show the home component at http://localhost:4200

2

2 Answers

0
votes

This is wrong URL

path: '',
component: AdminLayoutComponent,
children: [{
  path: '',
  component: HomeComponent
},

According to your configuration this is needed route for HomeComponent: "//"

Try to do next way

export const AppRoutes: Routes = [
  {
    path: '',
    component: AdminLayoutComponent,
    children: [{
      path: 'home',
      component: HomeComponent
    }, {
      path: 'posts',
      loadChildren: './posts/posts.module#PostsModule'
    },{
      path: '**',
      component: PageNotFoundComponent
    }]
  }
];
0
votes

When you land on Home Component it is redirected to empty path not /home. So try the following, It will help. What it does is whenever empty path is found it redirects to Out home component. Just try to add the lines I have written below >>> ADDED CODE STARTS HERE

    export const AppRoutes: Routes = [
  {
    path: '',
    component: AdminLayoutComponent,
    children: [{

     // >>> ADDED CODE STARTS HERE
      path: '',
      redirectTo: 'home',
      pathMatch: 'full'
    }, 
    {
      path: 'home',
      Component: HomeComponent
    },
    // >>> ADDED CODE ENDS HERE

    {
      path: 'posts',
      loadChildren: './posts/posts.module#PostsModule'
    },{
      path: '**',
      component: PageNotFoundComponent
    }]
  }
];