[英]Angular 2: How do I get params of a route from outside of a router-outlet
[英]How do I get access to route parameters in angular 2.0 from components not mapped to a route/router-outlet
我有以下路線
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.log記錄為“ undefined”。
當我在MetadataDisplayComponent中嘗試完全相同的ngOnInit時,我能夠console.log路徑沒有問題。
我幾乎可以肯定地說,這是因為TreeViewComponent與我的一條路線沒有關聯,因此無法訪問路線變量。 它位於路由器出口附近,但不在路由器出口內。
有什么辦法可以解決這個問題? 我意識到我可能已經以完全愚蠢的方式計划了布局,並且願意接受建議。
經過幾個小時的搜索同一件事,這才是有效的
在路由器出口外部的服務/組件內部
this.router.events.subscribe(val => {
if (val instanceof NavigationEnd) {
let r = this.route;
while (r.firstChild) {
r = r.firstChild;
}
r.params.subscribe(params => {
//do stuff with params['yourParam']
console.log(params);
});
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.