从根组件获取子路由参数(app.component)

时间:2017-06-12 07:27:17

标签: angular router

我的众神:

如何从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)"将参数解析为路线点;

请救救我!

1 个答案:

答案 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更新:

  1. 在服务中使用共享数据
  2. 应用-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);
      });
    }
    
    1. 尝试ngrx/Store