【问题标题】:How to pass parameters to routes in angular2.0如何在angular2.0中将参数传递给路由
【发布时间】:2016-08-02 05:40:56
【问题描述】:

我正在尝试使用路由参数但无法实现它,因为当我导入 Routeparams 时它显示错误,

我的模板,

    <h6 class="headingh6 nobottommargin"><a [routerLink]="['User',{{detail.firstname}}]">  {{detail.firstname}} </a></h6>

我的组件

import { Component,OnInit} from '@angular/core';
import { Route, RouteSegment, ROUTER_DIRECTIVES } from '@angular/router';

@Component({
selector: 'User', 
templateUrl: './components/society/society.html',
Directives: [ROUTER_DIRECTIVES]
})
export class User  {
id:any;
 constructor(routeSegment: RouteSegment) {
   this.id = routeSegment.getParam('id'); 
   console.log(this.id);   
 }
}

谁能帮帮我

我的路线

   import {provideRouter, RouterConfig} from '@angular/router';

  import {DemoPage} from './demo-page';

  import {User} from './components/user/user';


   export const routes: RouterConfig = [
   { path: '', redirectTo: '/login', terminal: true },
   { path: 'login', component:Login },
   { path: 'signup', component:SignUp },
   { path: 'demo', component: DemoPage, children: [
     { path: 'user', component:User },
     { path: 'requests', component:Requests },
   ]}
];

 export const APP_ROUTER_PROVIDERS = [
    provideRouter(routes)


  ];

【问题讨论】:

    标签: typescript angular


    【解决方案1】:
    <h6 class="headingh6 nobottommargin"><a [routerLink]="['User',detail.firstname]">{{detail.firstname}}</a></h6>
    

    不要将[]{{}} 一起使用。一个或另一个,但不能同时两个。

    要获取路由器参数,请使用

    constructor(private route: ActivatedRoute) {
      route.routerState.params.subscribe(p => console.log(p['id'));
    }
    

    另见Get route query params

    【讨论】:

    • 您使用的是什么路由器版本?当前路由器版本中没有RouteSegment
    • 可以有任何选择
    • 三个是 3 个(如果算上 ngrx 路由器,那么 4 个)Angular2 的不同路由器,每个路由器都有不同的版本。我更新了我对 V3.0.0-beta.2(Angular2 团队的最新版本)路由器的答案。 Angular2 团队的另外两个路由器已弃用。
    • 当我运行它时显示错误“无法绑定到'routerLink',因为它不是已知的本机属性”
    • 您需要在要使用&lt;router-outlet&gt;routerLink 的组件上添加@Component({ ..., directives: [ROUTER_DIRECTIVES]})`。
    【解决方案2】:

    您只想阅读 Querystring 参数吗?

    如果是,使用这个

    constructor(private route: ActivatedRoute) {
          console.log(this.route.snapshot.params.id);
       }
    

    在导入中你需要这个:

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

    当然,如果在路由配置中你有/:id,这将起作用

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-21
      • 2018-06-20
      • 2020-08-09
      • 1970-01-01
      • 2023-03-20
      • 2016-07-01
      • 2019-03-03
      相关资源
      最近更新 更多