How to pass parameters to routes in angular2.0

2020-05-06 11:20发布

问题:

I am trying to use the route params but not able to achieve it since when i importing the Routeparams it shows errors,,

My template,

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

My componenet

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);   
 }
}

Can someone help me

My routes

   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)


  ];

回答1:

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

Don't use [] together with {{}}. Either one or the other, but not both at the same time.

To get router parameters use

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

See also Get route query params



回答2:

Do you just want to read the Querystring param ?

if yes, use this

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

in the import you need this:

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

of course this will work if in the route config you have /:id