构造函数将首先运行。因此,您仍然可以在构造函数中获取路由信息,但是,您应该在ngAfterViewInit()生命周期挂钩中设置一个expandedPanel属性,而不是构造函数。
比如:
...
export class Component implements OnInit, AfterViewInit {
routerSubscription: Subscription;
expandPanel1 = false;
expandPanel2 = false;
urlInfo: string;
constructor(private router: Router) {
this.routerSubscription = this.router.events
.pipe(filter(event => event instanceof NavigationEnd))
.subscribe(event => {
urlInfo = event["url"];
});
}
...
setRoute(path: string) {
this.router.navigate([`home/${path}`]);
}
ngAfterViewInit(){
if (this.urlInfo.includes("/panel-1")) {
this.expandPanel1 = true;
}
else {
this.expandPanel2 = true;
}
}
...