我在app.component.html
:
<app-main-nav></app-main-nav>
<router-outlet></router-outlet>
这是我的路线:
const routes = [
{path: "", redirectTo: "home", pathMatch: "full"},
{
path: "posts", component: PostsComponent,
children: [{
path: ":id",
component: PostComponent
}];
}
]
我正在尝试访问PostComponent
中MaiNavComponent
页面中的参数,但会引发错误。
export class MainNavComponent implements OnInit {
constructor( private route: ActivatedRoute) {
route.params.subscribe(console.log)
}
}
如何从:id
获取PostComponent
的{{1}}?
我试着这样做:
MainNavComponent
我在这里得到一个空对象。
而且:
route.params.subscribe(console.log)
无法阅读财产&#39; params&#39;为null
答案 0 :(得分:1)
问题是ActivatedRoute
仅在插座(route-outlet
)中加载的组件内可用。在外部组件中,您可以注入路由器并按如下方式使用它:
export class MainNavComponent implements OnInit {
constructor(private router: Router) {}
ngOnInit() {
// Fires when the url changes
this.router.events.subscribe(data => {
// Only handle final active route
if (data instanceof NavigationEnd) {
// parsedUrl conatins params, queryParams
// and fragments for the active route
let parsedUrl = this.router.parseUrl(this.router.url);
console.log(parsedUrl);
}
});
}
}
我希望这会对你有所帮助。
答案 1 :(得分:0)
constructor(
private router: Router,
private activatedRoute: ActivatedRoute) {
}
ngOnInit() {
this.loadParams();
}
private loadParams(): void {
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
let activatedRoute = this.activatedRoute.firstChild;
while (!activatedRoute) {
activatedRoute = activatedRoute.firstChild;
}
const value = activatedRoute.snapshot.paramMap.get('parmeter key');
}
});
}
答案 2 :(得分:-1)
您必须快照以从URL.Uodate构造函数获取ID,如下所示
constructor( private route: ActivatedRoute) {
}
ngOnInit() {
// (+) converts string 'id' to a number
let id = +this.route.snapshot.params['id'];
}