Angular 2 : getting RouteParams from parent component

标签 angular angular2-routing

如何从父组件获取 RouteParams?

App.ts:

@Component({
  ...
})

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

export class HomeComponent {
  ...
}

然后,在 ParentComponent 中,我可以轻松获取用户名参数并设置子路由。

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');
  }

  ...
}

但是,我怎样才能在这些子组件中获得相同的“用户名”参数呢?做与上面相同的技巧,不这样做。因为这些参数是在 ProfileComponent 或其他地方定义的??

@Component({
  ...
})

export class ChildOneComponent {

  public username: string;

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

  ...
}

最佳答案

更新:

现在Angular2 final已经正式发布,正确的做法是:

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();
    }
}

原创:

这是我如何使用“@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/:childid

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

关于 Angular 2 : getting RouteParams from parent component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34500147/

相关文章:

typescript - 异步 HTTP 请求的顺序

Angular2 - 成功登录后重定向到调用url

Angular 2 Material 表单元素水平对齐

javascript - Angular2——使用 NgFor 时,每次 keyup 后双向绑定(bind)文本输入模糊

angular - 无法绑定(bind)到 'href',因为它不是已知的 native 属性

html - 平均堆栈 - Angular 2 网站未完全加载

angular - 如何在内存中使用两个不同 json 的 Web api

javascript - 为什么我必须导出我在 angular appModule 导入模块中使用的函数?

Angular 通用 + CkEditor5 : window is not defined

javascript - Angular2 将服务方法从回调更改为异步