Angular 即使在我以角度导航到父路由之后,也会调用子路由
在我的angular应用程序中,我有一个这样的父路由Angular 即使在我以角度导航到父路由之后,也会调用子路由,angular,angular-router,Angular,Angular Router,在我的angular应用程序中,我有一个这样的父路由',还有一个这样的子路由'child-route'。这是我的路线图 const routes: Routes = [ { path: '', component: DefaultComponent, canActivate: [AuthGuard], children: [ { path: '', component: FirstComponent, }, { path
'
,还有一个这样的子路由'child-route'
。这是我的路线图
const routes: Routes = [
{
path: '',
component: DefaultComponent,
canActivate: [AuthGuard],
children: [
{
path: '',
component: FirstComponent,
},
{
path: 'child-route',
component: AnotherComponent,
},
];
这是我的组件代码
export class FirstComponent {
constructor() {
console.log("parent");
}
}
export class AnotherComponent {
constructor(private router: Router) {
console.log("child");
this.router.navigate(['']);
}
}
现在,当我在浏览器中运行localhost:4200/child-route
时,这就是我在控制台中得到的结果
子-父-子
为什么它在导航到父路由时再次调用子路由。问题在于,默认情况下,它会尝试基于当前URL进行导航。请参见“命令”参数。因此,我认为您可以改为调用this.router.navigate(['../'])
,其行为类似于向上导航目录。或者您可以尝试将父对象作为“relativeTo”参数传入。您可以从注射的药物中获得:
构造函数(公共路由:ActivatedRoute){}
this.router.navigate(['],{relativeTo:route.parent})
子路径必须唯一,
您应该为FirstComponent提供一个路径,然后您的路由正常工作我将
home
定义为FirstComponent
的路径。仍获得相同的输出。尝试了这两种方法,但结果相同。无法复制: