Can RouteData in Angular 2 pass variables to route

2019-02-23 12:14发布

问题:

I would like to use the RouteConfig to pass a variable from my AppComponent to Coursescomponent, but the "data" property in route config can only pass constant parameter, and it cannot recognize "this". Is there a way to do this?

If not, what is a best practice to pass variables to routed components?

@Component({
    selector: 'app',
    template: `
    <router-outlet></router-outlet>
    `,

directives: [ROUTER_DIRECTIVES],
})

@RouteConfig([
    { path: '/courses'
      , name: 'Courses' 
      ,component: CoursesComponent
       ,data:{token:this.token}}  // this doesn't work -- cannot read property "token" of undefined

])

export class AppComponent  {
    token:string;
//I would change the token(string) in this component, and I want to pass this to the routed components

}

回答1:

You can use a shared service to share values between components.

See Global Events in Angular 2 for more details how to implement a shared service.

Alternatively you can inject the Router and call one of it's router.navigateXxx() functions where you pass additional data.



回答2:

I have achieved this by defining a dynamic route in the constructor. Here is an example

import {Router,ROUTER_DIRECTIVES} from 'angular2/router';
import {Component} from 'angular2/core';

@Component({
  selector: "app",
  template: '<router-outlet></router-outlet>',
  directives: [ROUTER_DIRECTIVES]
})
export class AppCmp{
  public token:string;
  constructor(private _router:Router){
    var config = [];
    if(!this._router.registry.hasRoute("Courses",AppCmp))
      config.push({ path: '/courses', name: 'Courses',component: CoursesComponent,data:{token:this.token});

    this._router.config(config)
  }
}