我正在尝试使用angular router
从我的页面导航。
我点击了button
,我正在导航到其他页面。
我目前的网址是:http://localhost:4200/user/12345567
。从这里我点击按钮导航
这是我的button
代码:
leaveArea(){
this.router.navigate([ 'account', 'dashboard'], {relativeTo: this.route});
}
我想点击导航到http://localhost:4200/account/dashboard
。
但相反,我被导航到http://localhost:4200
。一瞬间(可能是一毫秒甚至更短),我确实在它导航到http://localhost:4200/account/dashboard
之前将网址视为http://localhost:4200
。路由逻辑有问题吗?
编辑
我正在添加routeTrace
结果:
编辑
这是我的路由文件:
const appRoutes: Routes = [
{ path: "", component: HomeComponent },
{ path: "account/dashboard", component: AccountDashboardComponent},
{
path: "user/:id", component: UserComponent
}
];
@NgModule({
imports: [RouterModule.forRoot(appRoutes, { enableTracing: true })],
exports: [RouterModule]
})
export class AppRoutingModule {}
只需尝试像这样使用router.navigateByUrl
-
leaveArea(){
this.router.navigateByUrl('/account/dashboard');
}
PS:通过在字符串的开头附加/
将考虑从根级别进行路由。
您首先拥有空白路线。
它需要是最后的。
配置中的路由顺序很重要,这是设计的。路由器在匹配路由时使用第一匹配胜利策略,因此应将更具体的路由放置在不太具体的路由之上。 (https://angular.io/guide/router)
所以...
const appRoutes: Routes = [
{ path: "account/dashboard", component: AccountDashboardComponent},
{ path: "user/:id", component: UserComponent},
{ path: "", component: HomeComponent}
];
请尝试将您的路线更改为
const appRoutes: Routes = [
{ path: "", redirectTo: "home", pathMatch: "full" }
{ path: "home", component: HomeComponent },
{ path: "account/dashboard", component: AccountDashboardComponent},
{ path: "user/:id", component: UserComponent }
];
并将您的导航线更改为
this.router.navigate(['/account', 'dashboard']);