Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在angular2 RC5中获取路由参数_Angular_Typescript_Angular2 Routing - Fatal编程技术网

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

如何在angular2 RC5中获取路由参数,angular,typescript,angular2-routing,Angular,Typescript,Angular2 Routing,我已使用angular2将我的angular2项目升级为RC5-cli@webpack 我已提供如下路由: const appRoutes: Routes = [ { path: 'project-manager', component: ProjectManagerComponent }, { path: 'designer/:id', component:DesignerComponent } , {path: '',redirectTo: '/project-m

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

我已提供如下路由:

const appRoutes: Routes = [
    { path: 'project-manager', component: ProjectManagerComponent },  
    { path: 'designer/:id', component:DesignerComponent } ,
    {path: '',redirectTo: '/project-manager',pathMatch: 'full'} 
];
我使用routerLink重定向到designer组件,如下所示:

<a [routerLink]="['/designer', page._id]"><i class="fa fa-eye fa-fw"></i></a>

现在它被成功重定向,我可以在浏览器的地址栏中看到参数值


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

首先从
@angular/router
导入
ActivatedRoute

import { ActivatedRoute } from '@angular/router';
访问it构造函数,如下所示:

constructor(private route: ActivatedRoute){            
}
ngOnInit() {
  this.route.params.subscribe(params => {
    if (params['id']) {
    }
  });
}
订阅ngOnInit内部的参数更改,如下所示:

constructor(private route: ActivatedRoute){            
}
ngOnInit() {
  this.route.params.subscribe(params => {
    if (params['id']) {
    }
  });
}

我相信您需要使用来自路由器的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
    });
}
如果需要,请不要忘记从
@angular/core
导入
OnInit

N.B:您还可以使用
this.route.snapshot.params
同步访问它


编辑:

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

把我弄糊涂了。为什么我需要订阅当前活动url中的固定值?它不会改变。我有点惊讶没有像@Input这样的东西来处理这类事情。更新:对于那些感兴趣的人:没有必要从可观察到的网站上获得订阅,也没有必要在
OnDestroy
事件中取消订阅。这条路线是自己管理的。您实际上可以剪切
此.sub
。编辑答案以获得最新信息!