Bhushan Gadekar Bhushan Gadekar - 3 months ago 132
TypeScript Question

how to get route parameters in angular2 RC5

I have upgraded my angular2 project to

RC5
using
angular-cli@webpack
.

I have provide routing as below:

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


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.

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

Answer

I believe you need to use the ActivatedRoute from the router to manipulate your parameter. You need to setup an observable and get the router parameters you want.

import { Router, ROUTER_DIRECTIVES, ActivatedRoute } from '@angular/router';

...

constructor(public route: ActivatedRoute, ...) {
}

private sub: any;      // -> Subscriber
private mode: string;  // -> var I want to init with my route parameter

ngOnInit() {
    // get URL parameters
    this.sub = this.route
        .params
        .subscribe(params => {
            // Récupération des valeurs de l'URL
            this.mode = params['id']; // --> Name must match wanted paramter
    });
}

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