I'm having trouble with routes in an Angular2 application where using a button like this works fine:
<button [routerLink]="['/home/maincomponent']>Click</button>
But using the same route in a function fails - the page seems to load for a split second, then the application refreshes completely and lands me back at the main / root page, but there's no error on the console.
goToComponent() {
this.router.navigate(['/home/maincomponent']);
}
Also, navigating to the route just by entering the path in the browser loads the component fine without any error or redirect.
http://localhost:4000/#/home/component
Router Config:
const routes: Routes = [
{
path: 'home',
component: HomeComponent,
children: [{
path: '',
redirectTo: 'dashboard',
pathMatch: 'full'
},
{
path: 'dashboard',
component: DashboardComponent
},
{
path: 'search',
component: SearchComponent
},
{
path: 'maincomponent',
component: MainComponent
},
{
path: '**',
component: DashboardComponent
}]
}
];
@NgModule Config:
RouterModule.forRoot(routes,
{
useHash: true,
preloadingStrategy: PreloadAllModules
}),
I was looking in the wrong place for the problem. I'd bound the function call (click) to an
<a href="" (click)="goToComponent">LINK</a>
element, which fails.
Switching to
<span (click)="goToComponent">LINK</span>
element solves the problem.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.