从根组件获取子路由参数(app.component)
get child route parameters from root component(app.component)
天哪:
如何从app.component(根组件)获取子路由参数,在我的应用程序中,子路由可能是“/teaching/grade/1213”或“/part/sim/te/1232”;
如何从 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:当 then 端组件处于活动状态时,则触发 then 订阅;
第二:"this.router.parseUrl(data.url)" 将参数解析为路由点;
请救救我!
试试这个
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更新:
- 在服务中使用共享数据
app-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);
});
}
天哪:
如何从app.component(根组件)获取子路由参数,在我的应用程序中,子路由可能是“/teaching/grade/1213”或“/part/sim/te/1232”; 如何从 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:当 then 端组件处于活动状态时,则触发 then 订阅; 第二:"this.router.parseUrl(data.url)" 将参数解析为路由点;
请救救我!
试试这个
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更新:
- 在服务中使用共享数据
app-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);
});
}