Angular 2:从父组件获取RouteParams

Angular 2: getting RouteParams from parent component

如何从父组件获取 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');
  }

  ...
}

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

@Component({
  ...
})

export class ChildOneComponent {

  public username: string;

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

  ...
}

我找到了一个丑陋但有效的解决方案,方法是请求父(准确地说是第二个祖先)注入器,并从这里获取 RouteParams

类似

@Component({
  ...
})
export class ChildOneComponent {
  public username: string;

  constructor(injector: Injector) {
    let params = injector.parent.parent.get(RouteParams);

    this.username = params.get('username');
  }
}

正如 Günter Zöchbauer 所提到的,我使用 https://github.com/angular/angular/issues/6204#issuecomment-173273143 中的评论来解决我的问题。我使用 angular2/core 中的 Injector class 来获取父级的路由参数。结果 angular 2 不处理深度嵌套的路由。也许他们将来会添加。

constructor(private _issueService: IssueService,
            private _injector: Injector) {}

getIssues() {
    let id = this._injector.parent.parent.get(RouteParams).get('id');
    this._issueService.getIssues(id).then(issues => this.issues = issues);
}

您可以从注入器中获取子组件内部父路由的组件,然后从子组件中获取任何组件。在你这样的情况下

@Component({
  ...
})

export class ChildOneComponent {

  public username: string;

  constructor(
    public params: RouteParams
    private _injector: Injector

  ) {
    var parentComponent = this._injector.get(ParentComponent)

    this.username = parentComponent.username;
    //or
    this.username = parentComponent.params.get('username');
  }

  ...
}

如果您想为代码编写单元测试,将 Injector 实例传递给子组件中的构造函数可能不太好。

解决此问题的最简单方法是在父组件中提供服务 class,您可以在其中保存所需的参数。

@Component({
    template: `<div><router-outlet></router-outlet></div>`,
    directives: [RouterOutlet],
    providers: [SomeServiceClass]
})
@RouteConfig([
    {path: "/", name: "IssueList", component: IssueListComponent, useAsDefault: true}
])
class IssueMountComponent {
    constructor(routeParams: RouteParams, someService: SomeServiceClass) {
        someService.id = routeParams.get('id');
    }
}

然后您只需将相同的服务注入子组件并访问参数即可。

@Component({
    template: `some template here`
})
class IssueListComponent implements OnInit {
    issues: Issue[];
    constructor(private someService: SomeServiceClass) {}

    getIssues() {
        let id = this.someService.id;
        // do your magic here
    }

    ngOnInit() {
        this.getIssues();
    }
}

请注意,您应该在父组件装饰器中使用 "providers" 将此类服务范围限定在您的父组件及其子组件中。

我在 Angular 2 中推荐这篇关于 DI 和作用域的文章:http://blog.thoughtram.io/angular/2015/08/20/host-and-visibility-in-angular-2-dependency-injection.html

您不应尝试在 ChildOneComponent 中使用 RouteParams

改用RouteRegistry

@Component({
  ...
})

export class ChildOneComponent {

  public username: string;

  constructor(registry: RouteRegistry, location: Location) {
    route_registry.recognize(location.path(), []).then((instruction) => {
      console.log(instruction.component.params['username']);
    })
  }


  ...
}

更新: 从这个拉取请求开始(angular beta.9):https://github.com/angular/angular/pull/7163

您现在可以在没有 recognize(location.path(), []) 的情况下访问当前指令。

示例:

@Component({
  ...
})

export class ChildOneComponent {

  public username: string;

  constructor(_router: Router) {
    let instruction = _router.currentInstruction();
    this.username = instruction.component.params['username'];
  }

  ...
}

还没试过

这里有更多详细信息:

https://github.com/angular/angular/blob/master/CHANGELOG.md#200-beta9-2016-03-09 https://angular.io/docs/ts/latest/api/router/Router-class.html

更新 2: 来自 angular 2.0.0.beta15 的小改动:

现在 currentInstruction 不再是一个函数。此外,您必须加载 root 路由器。 (感谢@Lxrd-AJ 的报道)

@Component({
  ...
})

export class ChildOneComponent {

  public username: string;

  constructor(_router: Router) {
    let instruction = _router.root.currentInstruction;
    this.username = instruction.component.params['username'];
  }

  ...
}

我最终为 Angular 2 rc.1

编写了这种 hack
import { Router } from '@angular/router-deprecated';
import * as _ from 'lodash';

interface ParameterObject {
  [key: string]: any[];
};

/**
 * Traverse route.parent links until root router and check each level
 * currentInstruction and group parameters to single object.
 *
 * e.g.
 * {
 *   id: [314, 593],
 *   otherParam: [9]
 * }
 */
export default function mergeRouteParams(router: Router): ParameterObject {
  let mergedParameters: ParameterObject = {};
  while (router) {
    let currentInstruction = router.currentInstruction;
    if (currentInstruction) {
      let currentParams = currentInstruction.component.params;
      _.each(currentParams, (value, key) => {
        let valuesForKey = mergedParameters[key] || [];
        valuesForKey.unshift(value);
        mergedParameters[key] = valuesForKey;
      });
    }
    router = router.parent;
  }
  return mergedParameters;
}

现在在视图中我在视图中收集参数而不是读取RouteParams我只是通过路由器获取它们:

@Component({
  ...
})

export class ChildishComponent {

  constructor(router: Router) {
    let allParams = mergeRouteParams(router);
    let parentRouteId = allParams['id'][0];
    let childRouteId = allParams['id'][1];
    let otherRandomParam = allParams.otherRandomParam[0];
  }

  ...
}  

更新:

现在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 }]
    }
];

RC5 + @angular/router": "3.0.0-rc.1 解决方案: 似乎 this.router.routerState.queryParams 已被弃用。您可以通过这种方式获取父路由参数:

constructor(private activatedRoute: ActivatedRoute) {
}    

this.activatedRoute.parent.params.subscribe(
  (param: any) => {
    let userId = param['userId'];
    console.log(userId);
  });

在 RC6 中,路由器 3.0.0-rc.2(可能也适用于 RC5),您可以从 URL 获取路由参数作为快照如果参数不会改变,没有这个衬垫的可观察值:

this.route.snapshot.parent.params['username'];

不要忘记注入 ActivatedRoute 如下:

constructor(private route: ActivatedRoute) {};

FINAL 中,在 RXJS 的帮助下,您可以合并两个映射(来自子映射和父映射):

(route) => Observable
    .zip(route.params, route.parent.params)
    .map(data => Object.assign({}, data[0], data[1]))

其他可能的问题:

  • 在上面使用真的是个好主意吗 - 因为耦合(将子组件与父组件的参数耦合 - 不在 api 级别 - 隐藏耦合),
  • 就 RXJS 而言,它是正确的方法吗(需要铁杆 RXJS 用户反馈;)

使用 RxJS 的 Observable.combineLatest,我们可以获得接近惯用参数处理的东西:

import 'rxjs/add/operator/combineLatest';

import {Component} from '@angular/core';
import {ActivatedRoute, Params} from '@angular/router';
import {Observable} from 'rxjs/Observable';

@Component({ /* ... */ })
export class SomeChildComponent {
  email: string;
  id: string;

  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    Observable.combineLatest(this.route.params, this.route.parent.params)
        .forEach((params: Params[]) => {
          this.id = params[0]['id'];
          this.email = params[1]['email'];
        });
  }
}

您可以在快照上执行以下操作,但如果它发生变化,您的 id 属性 将不会更新。

此示例还展示了如何订阅所有祖先参数更改并通过合并所有参数可观察值来查找您感兴趣的参数。但是,请谨慎使用此方法,因为可能有多个祖先具有相同的参数 key/name.

import { Component } from '@angular/core';
import { ActivatedRoute, Params, ActivatedRouteSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Subscription } from 'rxjs/Subscription';
import 'rxjs/add/observable/merge';

// This traverses the route, following ancestors, looking for the parameter.
function getParam(route: ActivatedRouteSnapshot, key: string): any {
  if (route != null) {
    let param = route.params[key];
    if (param === undefined) {
      return getParam(route.parent, key);
    } else {
      return param;
    }
  } else {
    return undefined;
  }
}

@Component({ /* ... */ })
export class SomeChildComponent {

  id: string;

  private _parameterSubscription: Subscription;

  constructor(private route: ActivatedRoute) {
  }

  ngOnInit() {
    // There is no need to do this if you subscribe to parameter changes like below.
    this.id = getParam(this.route.snapshot, 'id');

    let paramObservables: Observable<Params>[] =
      this.route.pathFromRoot.map(route => route.params);

    this._parametersSubscription =
      Observable.merge(...paramObservables).subscribe((params: Params) => {
        if ('id' in params) {
          // If there are ancestor routes that have used
          // the same parameter name, they will conflict!
          this.id = params['id'];
        }
      });
  }

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

从Angular中的父组件获取RouteParams 8 -

我有路线http://localhost:4200/partner/student-profile/1234/info

上级路线 - 学生资料

参数 - 1234 (student_id)

子路由 - 信息


正在访问子路由中的参数(信息)-

导入

import { ActivatedRoute, Router, ParamMap } from '@angular/router';

构造函数

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

正在访问父路由参数

this.activatedRoute.parent.paramMap.subscribe((params: ParamMap) => this.studentId = (params.get('student_id')));


现在,我们的变量 studentId 具有参数值。