Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/google-maps/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 即使在我以角度导航到父路由之后,也会调用子路由_Angular_Angular Router - Fatal编程技术网

Angular 即使在我以角度导航到父路由之后,也会调用子路由

Angular 即使在我以角度导航到父路由之后,也会调用子路由,angular,angular-router,Angular,Angular Router,在我的angular应用程序中,我有一个这样的父路由',还有一个这样的子路由'child-route'。这是我的路线图 const routes: Routes = [ { path: '', component: DefaultComponent, canActivate: [AuthGuard], children: [ { path: '', component: FirstComponent, }, { path

在我的angular应用程序中,我有一个这样的父路由
'
,还有一个这样的子路由
'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
的路径。仍获得相同的输出。尝试了这两种方法,但结果相同。无法复制: