Mikkel Mikkel - 4 days ago 4
TypeScript Question

Send string value to component on url navigation in angular 2

I need some help with passing a string (bookingNumber) to a component when I'm using the router.navigate method.

Right now, I have a service called bookingsService which has a method like this code here:

redirectToBookingPage(bookingNumber: string) {

var bookingNumber = bookingNumber;

this.router.navigate(['../Main']);
}


The redirection works, but how can I send the value bookingNumber and load it in the component?

The component which should get this value is here:

import { Injectable, Inject, Component } from 'angular2/core';
import {RouteConfig, Router, ROUTER_DIRECTIVES} from 'angular2/router';
import {FORM_PROVIDERS} from 'angular2/common';

@Component({
selector: 'main-component',
providers: [...FORM_PROVIDERS],
directives: [...ROUTER_DIRECTIVES ],
styles: [`
agent {
display: block;
}
`],
pipes: [],
template: `
<div class="column small-12 main-area">
<div class="content content-container">
<div class="is-loading"></div>
<div class="row uncollapse login-container">
<div class="column small-12">
<div class="row">
<h1>Main</h1>

</div>
</div>
</div>
</div>
</div>
`,
bindings: [],
})

@Injectable()
export class MainComponent {

constructor() {


}

}


I think before I load the html, I should run a method in the constructor to get the bookingNumber from the url?

Answer

First, you must configure your Main route to accept param.

@RouteConfig([
 { component: MainComponent, path: "/:id" }
])

Then, when redirecting you must pass param value like this:

this.router.navigate(['../Main', {id: 2}]);

Finally, in your MainComponent you must catch that param:

export class MainComponent {
 constructor(params: RouteParams) {
  let value: any = params.get("id");
 }
}

https://angular.io/docs/ts/latest/api/router/index/Params-type-alias.html

Comments