gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:06:15 24 4
gpt4 key购买 nike

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

我已经提供了如下路由:

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

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

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

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

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

最佳答案

我相信您需要使用路由器中的 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

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


已编辑:

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

关于angular - 如何在angular2 RC5中获取路由参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39163734/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com