我有以下路由
const routes: Routes = [
{ path: 'metadata/:path', component: MetadataDisplayComponent },
{ path: 'data/:path', component: DataDisplayComponent }
]
这是我的AppComponent,其中注入了元数据/数据显示组件 .
@Component({
selector: 'my-app',
template: `
<tree-view></tree-view> <!-- a component the displays a tree like hierarchy of the path -->
<router-outlet></router-outlet>
`
})
基本上,我总是希望树视图在那里做它的事情,无论元数据/数据状态如何,但我需要根据路由中的参数对其进行初始化 .
现在,我的问题是我的“树视图”组件需要访问我在2条路由中定义的变量“:path” . 当我尝试以下(在我的树视图组件内)
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
@Component({
selector : 'tree-view',
// etc...
})
export class TreeViewComponent implements OnInit {
private sub: any;
contstructor(
@Inject(ActivatedRoute) private route: ActivatedRoute
) {}
ngOnInit(): void {
this.sub = this.route.params.subscribe(params => {
console.log(params['path']); // this logs "undefined"
});
}
// added this as per the suggestion in the comments
ngAfterViewInit(): void {
this.sub = this.route.params.subscribe(params => {
console.log(params['path']); // this logs "undefined"
});
}
// etc...
}
我尝试访问“path”参数是不成功的,它是console.logged为“undefined” .
当我在MetadataDisplayComponent中尝试完全相同的ngOnInit时,我能够console.log路径没问题 .
我几乎肯定这是因为我的TreeViewComponent没有与我的一条路线相关联,因此无法访问路线变量 . 它住在旁边,但不在路由器插座内 .
我有什么方法可以解决这个问题吗?我意识到我可能已经以完全愚蠢的方式规划了布局,并且愿意接受建议 .
1 回答
经过几个小时寻找同样的事情,这是有效的
在路由器插座外的服务/组件内部