我的众神:
如何从app.component(根组件)获取子路由参数,在我的应用程序中,子路由可能是" / teaching / grade / 1213"或" / part / sim / te / 1232&#34 ;; 如何从app.component获取参数?
ngOnInit() {
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(data.url).root.children;
console.log(parsedUrl.primary.segments);
}
});
}
在上面的代码中,有两个问题: first:当end组件处于活动状态时,则触发subscribe; 第二个:" this.router.parseUrl(data.url)"将参数解析为路线点;
请救救我!
答案 0 :(得分:0)
试试这个
constructor(private router: Router, private route: ActivatedRoute) { }
ngOnInit() {
this.route.snapshot.params['id']
// or
this.route.params.subscribe(params => {
console.log(params['id']);
});
}
2017/6/13更新:
应用-state.service.ts 强>
@Injectable()
export class AppState {
params = new BehaviorSubject(undefined);
setParams(val: any) {
this.params.next(val);
}
}
<强> child.component.ts 强>
constructor(private route: ActivatedRoute, private appState: AppState) { }
ngOnInit() {
this.route.params.subscribe(params => {
this.appState.setParams(params['id']);
});
}
<强> app.component.ts 强>
ngOnInit() {
this.appState.params.subscribe(val => {
console.log(val);
});
}