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

Angular2 Routing - Passing data from parent component to a sub-child component

本文关键字:组件 路由 数据 Angular2      更新时间:2023-09-26

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

父级.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组件。我在plunker 上重新生成了这个问题

通常一个服务用于此用例

@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##双向服务