Angular:如何在父组件中订阅子路径?

时间:2018-11-26 14:11:05

标签: angular

我的模块中有以下路线:

const userManagementRoutes: Routes = [
  {
    path: 'userManagement',
    component: UserManagementComponent,
    children: [
      {
        path: 'users',
        component: UsersComponent
      },
      {
        path: 'user-groups',
        component: UserGroupsComponent
      },
      ... (many other routes)
  }
];

我想订阅父组件中的URL,以便父组件知道何时渲染子对象。例如:当网址更改为

http://localhost:4200/userManagement/users

 http://localhost:4200/userManagement/user-groups
父母应该知道的。

我尝试执行以下操作,但是这些方法都不起作用:

export class UserManagementComponent implements OnInit {

  constructor(private route: ActivatedRoute) {  }

  ngOnInit() {
    this.route.firstChild.params.subscribe(params => {
      console.log(params);
    });

    this.route.params.subscribe(params => {
      console.log(params);
    });

    this.route.url.subscribe(params => {
      console.log(params);
    });
  }
}

2 个答案:

答案 0 :(得分:1)

您可以像这样订阅路由器事件:

import { Router } from '@angular/router';
this.router.events.subscribe(event => {
      if (event instanceof NavigationEnd) {
        const currentUrl = event.url;
      }
    });

这将在每次更改路线时通知您。尽管请记住,这是所有路由器事件,而不仅仅是子路由更改。

希望这会有所帮助。

亲切的问候克里斯

答案 1 :(得分:0)

根据本期here,您所寻找的内容没有直接的解决方案。但是有一种解决方法,它会监视每条路线的更改,然后您可以检查一下是否是第一个孩子。

在此处复制相同的代码

this._router.events
      .pipe(
        filter(event => event instanceof NavigationEnd),
        switchMap(
          () =>
            (this._route.firstChild && this._route.firstChild.params) ||
            observableOf({}),
        ),
      )
      .subscribe(params => console.log(params));