Can RouteData in Angular 2 pass variables to routed components from parent component?

[亡魂溺海] 提交于 2019-12-04 03:46:20

问题


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


来源:https://stackoverflow.com/questions/36108771/can-routedata-in-angular-2-pass-variables-to-routed-components-from-parent-compo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!