如何从父组件获取路由图?

App.ts:

@Component({
  ...
})

@RouteConfig([
  {path: '/', component: HomeComponent, as: 'Home'},
  {path: '/:username/...', component: ParentComponent, as: 'Parent'}
])

export class HomeComponent {
  ...
}

然后,在ParentComponent中,我可以轻松获得用户名param并设置子路由.

Parent.ts:

@Component({
  ...
})

@RouteConfig([
  { path: '/child-1', component: ChildOneComponent, as: 'ChildOne' },
  { path: '/child-2', component: ChildTwoComponent, as: 'ChildTwo' }
])

export class ParentComponent {

  public username: string;

  constructor(
    public params: RouteParams
  ) {
    this.username = params.get('username');
  }

  ...
}

但是,我怎样才能在这些子组件中获得相同的"username"参数呢?做同样的把戏,如上所述,没有做到这一点.因为这些参数是在ProfileComponent或其他地方定义的??

@Component({
  ...
})

export class ChildOneComponent {

  public username: string;

  constructor(
    public params: RouteParams
  ) {
    this.username = params.get('username');
    // returns null
  }

  ...
}

推荐答案

UPDATE:

现在Angular2决赛正式发布,正确的方法如下:

export class ChildComponent {

    private sub: any;

    private parentRouteId: number;

    constructor(private route: ActivatedRoute) { }

    ngOnInit() {
        this.sub = this.route.parent.params.subscribe(params => {
            this.parentRouteId = +params["id"];
        });
    }

    ngOnDestroy() {
        this.sub.unsubscribe();
    }
}

ORIGINAL:

下面是我如何使用"@angular/router":"3.0.0-alpha.6"包实现的:

export class ChildComponent {

    private sub: any;

    private parentRouteId: number;

    constructor(
        private router: Router,
        private route: ActivatedRoute) {
    }

    ngOnInit() {
        this.sub = this.router.routerState.parent(this.route).params.subscribe(params => {
            this.parentRouteId = +params["id"];
        });
    }

    ngOnDestroy() {
        this.sub.unsubscribe();
    }
}

在本例中,路由的格式如下:/Parent/:ID/Child/:Chilid

export const routes: RouterConfig = [
    {
        path: '/parent/:id',
        component: ParentComponent,
        children: [
            { path: '/child/:childid', component: ChildComponent }]
    }
];

Angular相关问答推荐

角路径S异步旋转变压器仍可观察到

使用指令的 Angular 自定义验证在 ng-change 中无法正常工作

Angular 信号 - 使用 mutate() 与使用 forEach() react 性

使用 RXJS 进行空闲/不活动跟踪

显示带有数组子列的标题表 - Angular

Summernote 文本区域的输入字段文本验证失败

通过 SignalR 事件组件重定向Angular 页面后不起作用

当访问令牌在 MSAL for Angular 中过期时如何重定向用户?

Angular:显示带有嵌套子项的内容投影

根据变量值更改按钮样式

为什么 Redux 中的对象应该是不可变的?

Angular2:更新数组时*ngFor不更新

Angular 2在单击子项时防止单击父项

Angular Material 模态对话框周围的空白

检测指令中输入值何时更改

`[(ngModel)]` vs `[(value)]`

Angular 6在输入键上添加输入

使用 DomSanitizer 绕过安全性后,安全值必须使用 [property]=binding

交替行 colored颜色 angular material表

Angular 2 单元测试 - 出现错误无法加载ng:///DynamicTestModule/module.ngfactory.js