我有一个带有主路由器插座和辅助路由器的应用程序 - oultet, 这是我的两个路由器插座的模板
<div>
<!-- links to primary outlet -->
<a routerLink="/">left 1</a><br>
<a routerLink="/left2">left 2</a><br>
<!-- links to right outlet -->
<a [routerLink]="[{outlets:{right:'right1'}}]">right 1</a><br>
<a [routerLink]="[{outlets:{right:'right2'}}]">right 2</a><br>
<a [routerLink]="[{outlets:{right:null}}]">clear right</a><br>
</div>
<div style="width:48%;float:left;border:1px solid red;margin-top:20px;padding:2px;">
<h2>Primary Outlet</h2><hr/>
<router-outlet></router-outlet>
</div>
<div style="width:48%;float:right;border:1px solid green;margin-top:20px;padding:2px;">
<h2>Right Outlet</h2><hr/>
<router-outlet name="right"></router-outlet>
</div>
这是我的路线定义
RouterModule.forRoot([
{
path : "",
component : Left1
},
{
path : "left2",
component : Left2
},
{
path : "right1",
outlet:'right',
component : Right1
},
{
path : "right2",
outlet:'right',
component : Right2
}
]
在app组件中,我将一个监听器附加到router.events
,我想知道哪个插座正在处理当前导航。
export class App {
private evtSub;
constructor(router:Router){
this.evtSub = router.events.subscribe(e=>{
//I assume this would log the current routes outlet, but it always logs 'primary'
console.log("router.routerState.root.outlet is::", router.routerState.root.outlet);
if(e instanceof RoutesRecognized){
//this would sure log the current route since we are on the route event, but still no luck
console.log("RoutesRecognized outlet is ::",e.state.root.outlet);
}
})
}
}
问题是routerState.root.outlet
始终是主要的&#39;即使当前路线是“正确的”
(我试图在子组件和模块中监听,我总是得到相同的行为)
以下是具有上述行为https://plnkr.co/edit/csIWByyMSziTaAgmhTuC?p=preview
的傻瓜答案 0 :(得分:1)
您可以使用 ActivatedRoute 收听当前路线。
constructor(private actRoute: ActivatedRoute){}
....
console.log(this.actRoute.outlet.toString());
通过上面的使用,您将获得当前激活的路由器插座名称。
编辑:在right1组件中检查
@Component({
selector : "right1",
template : "this is right1"
})
export class Right1{
constructor(router:Router, route:ActivatedRoute){
console.log("Right1 route.outlet (ActivatedRoute) is:",route.outlet);
}
}