Angular 角度:如何订阅父组件中的子路径?
我的模块中有以下路径:Angular 角度:如何订阅父组件中的子路径?,angular,Angular,我的模块中有以下路径: const userManagementRoutes: Routes = [ { path: 'userManagement', component: UserManagementComponent, children: [ { path: 'users', component: UsersComponent }, { path: 'user-groups',
const userManagementRoutes: Routes = [
{
path: 'userManagement',
component: UserManagementComponent,
children: [
{
path: 'users',
component: UsersComponent
},
{
path: 'user-groups',
component: UserGroupsComponent
},
... (many other routes)
}
];
我希望订阅父组件中的URL,以便父组件知道何时呈现子组件。例如:当URL从
http://localhost:4200/userManagement/users
到
家长应该知道
我尝试了以下方法,但这两种方法都不起作用:
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);
});
}
}
您可以订阅路由器事件,如下所示:
import { Router } from '@angular/router';
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
const currentUrl = event.url;
}
});
这将在每次发生路线更改时通知您。尽管请记住,这是所有路由器事件,而不仅仅是子路由更改
希望这有帮助
根据这个问题,没有直接的解决方案来解决您所寻找的问题。但是一个解决办法,注意每一条路线的变化,然后你可以检查这是否是第一个孩子左右
在这里复制相同的代码
this._router.events
.pipe(
filter(event => event instanceof NavigationEnd),
switchMap(
() =>
(this._route.firstChild && this._route.firstChild.params) ||
observableOf({}),
),
)
.subscribe(params => console.log(params));
谢谢但是,我想知道是否有更优雅的解决方案。我觉得这一定是一个更好的方法,也许有,但这是我目前用来实现同样的目标。您可以检查当前url,看看它是否包含您的父url,然后进行计算。我认为这是一个公平的例子,虽然没有理想的订阅父路由和监听子路由变得活跃那么干净。对不起:)
this._router.events
.pipe(
filter(event => event instanceof NavigationEnd),
switchMap(
() =>
(this._route.firstChild && this._route.firstChild.params) ||
observableOf({}),
),
)
.subscribe(params => console.log(params));