如何在angular2 RC5中获取路线参数 [英] how to get route parameters in angular2 RC5

查看:68
本文介绍了如何在angular2 RC5中获取路线参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用angular-cli@webpack将我的angular2项目升级到了RC5.

I have upgraded my angular2 project to RC5 using angular-cli@webpack.

我提供的路由如下:

const appRoutes: Routes = [
    { path: 'project-manager', component: ProjectManagerComponent },  
    { path: 'designer/:id', component:DesignerComponent } ,
    {path: '',redirectTo: '/project-manager',pathMatch: 'full'} 
];

,并且我使用routerLink重定向到Designer Component:

and I am redirecting to designer Component using routerLink as :

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

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

Now It is getting redirected successfully and I am able to see param value in address bar of the browser.

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

Now I want to know , How can I access this parameter in DesignerComponent in angular2 RC5.

推荐答案

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

I believe you need to use the ActivatedRoute from the router to manipulate your parameter.

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.

Don't forget to import OnInit from @angular/core if you need it as well.

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

N.B : You can also use this.route.snapshot.params to access it synchronously.

  • 清理以避免订阅,因为NG2路由器自己管理订阅.
  • 避免使用HTML中可能使用的私有变量,以免破坏AOT编译.
  • 已清除ROUTER_DIRECTIVES,因为已弃用.
  • 避免使用字符串文字:params ['id'] => params.id
  • 使用TypeScript输入参数
  • Cleanup to avoid subscription because the NG2 router manages his subscriptions on his own.
  • Avoid using private variables that might be used in the HTML to avoid breaking AOT compilation.
  • Cleaned ROUTER_DIRECTIVES because it's deprecated.
  • Avoid using string literal : params['id'] => params.id
  • Type your parameter with TypeScript if you have it

这篇关于如何在angular2 RC5中获取路线参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆