Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 670
Bhushan Gadekar Avatar asked Aug 26 '16 10:08

Bhushan Gadekar


2 Answers

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

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

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


EDITED :

  • 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
like image 62
Alex Beugnet Avatar answered Sep 28 '22 00:09

Alex Beugnet


First import ActivatedRoute from @angular/router.

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

access it constructor as below :

constructor(private route: ActivatedRoute){            
}

subscribe to params change inside ngOnInit as below :

ngOnInit() {
  this.route.params.subscribe(params => {
    if (params['id']) {
    }
  });
}
like image 29
ranakrunal9 Avatar answered Sep 28 '22 00:09

ranakrunal9