1

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 Answers 2

0

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
    }]
  }
];
Sign up to request clarification or add additional context in comments.

2 Comments

this config is showing the home component at localhost:4200/home and 'page not found' is showing for root. But i wanted to show the home component at root
Do you import it? import { AdminLayoutComponent} from './your path';
0

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
    }]
  }
];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.