Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use RouteData in Angular2 Beta?

I'm facing problems when I try to use RouteData in Angular2 Beta using TypeScript.

I inject it in the constructor and import it properly

import {RouteConfig, Router, RouteData} from 'angular2/router';

export class App {
    constructor(public router: Router, public data: RouteData) {
        // router works - routedata not
    }
}

I'm getting No provider for RouteData! (App -> RouteData).

If I include it into the component annotation like this

@Component({
  //..
  providers: [RouteData]
})

I get this error: Cannot resolve all parameters for RouteData(?). Make sure they all have valid type or annotations.

like image 609
gerric Avatar asked Jan 25 '16 14:01

gerric


1 Answers

RouteData provides data to your child component by the RouteConfig in your parent component. There shouldn't be any need to use it in your AppComponent.

To use it you should provide a RouteConfig in your AppComponent like this:

@RouteConfig([
  {path: '/child', name: 'Child', component: ChildCmp, data: {item: 'hi there'}}
])

Your ChildComponent should then inject RouteData and is able to retrieve the parameter set in the route like this:

export class ChildCmp {
  constructor(@Inject(RouteData) private data:RouteData) {
    this.data.get("item")
  }
}
like image 60
Rutger van Baren Avatar answered Sep 28 '22 15:09

Rutger van Baren