Bhushan Gadekar Bhushan Gadekar - 5 months ago 905
Javascript Question

Angular 2: Passing Data to Routes?

I am working on this angular2 project in which I am using

ROUTER_DIRECTIVES
to navigate from one component to other.

There are 2 components. i.e.
PagesComponent
&
DesignerComponent
.

I want to navigate from PagesComponent to DesignerComponent.

So far its routing correctly but I needed to pass
page
Object so designer can load that page object in itself.

I tried using RouteParams But its getting page object
undefined
.

below is my code:

pages.component.ts

import {Component, OnInit ,Input} from 'angular2/core';
import { GlobalObjectsService} from './../../shared/services/global/global.objects.service';
import { ROUTER_DIRECTIVES, RouteConfig } from 'angular2/router';
import { DesignerComponent } from './../../designer/designer.component';
import {RouteParams} from 'angular2/router';

@Component({
selector: 'pages',
directives:[ROUTER_DIRECTIVES,],
templateUrl: 'app/project-manager/pages/pages.component.html'
})
@RouteConfig([
{ path: '/',name: 'Designer',component: DesignerComponent }
])

export class PagesComponent implements OnInit {
@Input() pages:any;
public selectedWorkspace:any;
constructor(private globalObjectsService:GlobalObjectsService) {
this.selectedWorkspace=this.globalObjectsService.selectedWorkspace;
}
ngOnInit() { }
}


In the html, I am doing following:

<scrollable height="300" class="list-group" style="overflow-y: auto; width: auto; height: 200px;" *ngFor="#page of pages">
{{page.name}}<a [routerLink]="['Designer',{page: page}]" title="Page Designer"><i class="fa fa-edit"></i></a>
</scrollable>


In the DesignerComponent constructor I have done the following:

constructor(params: RouteParams) {
this.page = params.get('page');
console.log(this.page);//undefined
}


So far its routing correctly to designer, but when I am trying to access
page
Object in designer then its showing
undefined
.
Any solutions?

Answer

You can't pass objects using router params, only strings because it needs to be reflected in the URL. It would be probably a better approach to use a shared service to pass data around between routed components anyway.

The old router allows to pass data but the new (RC.1) router doesn't yet.

Update

data was re-introduced in RC.4 How do I pass data in Angular 2 components while using Routing?