如何在angular2 RC5中获取路径参数

Bhu*_*kar 10 typescript angular2-routing angular

我已将angular2项目升级为RC5使用angular-cli@webpack.

我提供如下路由:

const appRoutes: Routes = [
    { path: 'project-manager', component: ProjectManagerComponent },  
    { path: 'designer/:id', component:DesignerComponent } ,
    {path: '',redirectTo: '/project-manager',pathMatch: 'full'} 
];
Run Code Online (Sandbox Code Playgroud)

我使用routerLink重定向到设计器组件:

<a [routerLink]="['/designer', page._id]"><i class="fa fa-eye fa-fw"></i></a>
Run Code Online (Sandbox Code Playgroud)

现在它被重定向成功,我能够在浏览器的地址栏中看到param值.

现在我想知道,如何在angular2 RC5中的DesignerComponent中访问此参数.

Ale*_*net 15

我相信您需要使用路由器中的ActivatedRoute来操作您的参数.

import { ActivatedRoute } from '@angular/router';

...

constructor(private route: ActivatedRoute, ...) {
}

// TODO :: Add type
value: any;  // -> wanted parameter (use your object type)

ngOnInit() {
    // get URL parameters
    this.route.params.subscribe(params => {
      this.value = params.id; // --> Name must match wanted parameter
    });
}
Run Code Online (Sandbox Code Playgroud)

不要忘了导入OnInit@angular/core,如果你需要它.

注意:您也可以使用this.route.snapshot.params它同步访问它.


编辑:

  • 清理以避免订阅,因为NG2路由器自己管理他的订阅.
  • 避免使用可能在HTML中使用的私有变量来避免破坏AOT编译.
  • 清理,ROUTER_DIRECTIVES因为它已被弃用.
  • 避免使用字符串文字:params ['id'] => params.id
  • 如果您有参数,请使用TypeScript键入您的参数

  • 让我困惑的颜色.为什么我需要订阅当前活动网址中的固定值?它不会改变.我有点惊讶的是,没有类似@Input的东西来处理这种事情. (3认同)

ran*_*al9 5

首先ActivatedRoute@angular/router.

import { ActivatedRoute } from '@angular/router';
Run Code Online (Sandbox Code Playgroud)

访问它的构造函数如下:

constructor(private route: ActivatedRoute){            
}
Run Code Online (Sandbox Code Playgroud)

在ngOnInit中订阅params更改如下:

ngOnInit() {
  this.route.params.subscribe(params => {
    if (params['id']) {
    }
  });
}
Run Code Online (Sandbox Code Playgroud)