Angular2 Routing - 将数据从父组件传递到子子组件

时间:2016-05-03 06:27:57

标签: javascript routing angular

我正在尝试将一个简单的字符串对象从父组件传递给子子组件。我尝试过以下方式:

parent.ts

import {Component} from 'angular2/core';
import {Router,ROUTER_DIRECTIVES,ROUTER_PROVIDERS,RouteConfig} from 'angular2/router';
import {ChildCmp} from "./child";
import {bootstrap} from 'angular2/platform/browser';

@Component({
    selector: 'app',
    template:`
    <router-outlet></router-outlet>
    `,
    directives: [ROUTER_DIRECTIVES]
})
export class ParentCmp{
    public data = "Some data from parent.";
    constructor (private _router:Router){
        var config = [];
        if(!this._router.registry.hasRoute("Child",ParentCmp))
            config.push({path: "/child/...",component:ChildCmp,name: 'Child',useAsDefault:true, data: {"data": this.data}});

        this._router.config(config);
    }
}

bootstrap(ParentCmp,[
    ROUTER_PROVIDERS
]);

child.ts

import {Component} from 'angular2/core';
import {RouteData,Router,ROUTER_DIRECTIVES,RouteConfig} from 'angular2/router';
import {SubChildCmp} from "./sub_child";

@Component({
    selector: 'child',
    template: `<router-outlet></router-outlet>`,
    directives: [ROUTER_DIRECTIVES]
})
@RouteConfig([

])
export class ChildCmp{
    public data:Object;
    constructor(private _data:RouteData,private _router:Router){

        this.data = this._data.get("data");

        var config = [];
        if(!this._router.registry.hasRoute("SubChild",ChildCmp))
            config.push({path:"/sub_child",component: SubChildCmp,name:"SubChild", useAsDefault:true, data:{"data":this.data}});

        this._router.config(config);
    }
}

sub_child.ts

import {Component} from 'angular2/core';
import {RouteData} from 'angular2/router';

@Component({
    selector: "sub-child",
    template: `Data from parent is -->
    {{data}}
    `
})
export class SubChildCmp{
    public data:Object;

    constructor(private _data:RouteData){

        this.data = this._data.get("data");
    }
}

但我得到一个空白页面。看起来child.ts中的路由配置未正确配置。我怎样才能做到这一点?我只想将parent组件中的一些数据传递给sub-child组件。我重新制作了问题here on plunker

1 个答案:

答案 0 :(得分:6)

通常,服务用于此用例

@Injectable
export class SharedData {
  data;
}
@Component({
    selector: 'app',
    providers: [SharedData],
    template:`
    <router-outlet></router-outlet>
    `,
    directives: [ROUTER_DIRECTIVES]
})
export class ParentCmp{
    public data = "Some data from parent.";
    constructor (private _router:Router, private _sharedData:SharedData){
        var config = [];
        if(!this._router.registry.hasRoute("Child",ParentCmp))
            _sharedData.data = this.data;
        }
    }
}
export class SubChildCmp{
    public data:Object;

    constructor(_sharedData:SharedData){

        this.data = _sharedData.data;
    }
}

如果存在时间问题,可能需要将ObservableBehaviorSubjectsubscribe()一起使用,例如SubChildCmpParentCmp设置之前读取值时它

有关详细信息,请参阅https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service