Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 Routing always redirect to root path

I'm using Angular 2 rc4 and I've used the new routing like this

const routes: RouterConfig = [{
    path: '',
    component: PublicLayoutComponent,
    children: [
        { path: '', component: HomeComponent},
        { path: 'login', component: LoginComponent}
    ]
}]

for this code i cannot access the route /login I just want to know what's wrong it's always redirect to the root, please help

like image 804
medhatdawoud Avatar asked Aug 08 '16 23:08

medhatdawoud


2 Answers

This is an old thread - but no answer yet. If it helps anybody - I found that for my case by adding this to the RouterModule.forRoot options:

RouterModule.forRoot(appRoutes,
      { enableTracing: true } // <-- debugging purposes only
)

Angular.io router docs

I then found that a nested component was throwing an exception. After fixing, my routing worked. What was happening was that the routing was working it was just blowing up when it reached the load of that 1 component so angular just quits the page load and defaults to base URL. This is presumably for security reasons in case your failing component is affecting in page security?

like image 97
Richard Strickland Avatar answered Sep 20 '22 02:09

Richard Strickland


You have the generic path '' as the first element, but you do not have pathMatch set to full, so that path matches everything. Based on current angular router config it will find the first match in the routes list and send the user there, in this case '' will match everything so it always just goes there and doesn't bother going further down the routes list. See the documentation here: https://angular.io/guide/router#configuration

I think you should have:

const routes: RouterConfig = [{
    path: '',
    component: PublicLayoutComponent,
    children: [
        { path: '', component: HomeComponent, pathMatch: 'full'},
        { path: 'login', component: LoginComponent}
    ]
}]
like image 38
Alex Egli Avatar answered Sep 23 '22 02:09

Alex Egli