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



我的上帝:

如何从app.component(根组件(获取子路由参数,在我的应用程序中,子路由可以是"/教学/年级/1213"或"/part/sim/te/1232";如何从应用程序组件获取参数?

    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:当终端组件处于活动状态时,触发订阅;第二:"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 更新:

  1. 在服务中使用共享数据

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);
  });
}
  1. 试用 ngrx/存储

最新更新