更新到 rc.4:当尝试在angular 2中的同级组件之间传递数据时,现在最简单的方法(angular.rc.4)是利用angular2的分层依赖注入并创建共享服务。
以下是服务:
import {Injectable} from '@angular/core';
@Injectable()
export class SharedService {
    dataArray: string[] = [];
    insertData(data: string){
        this.dataArray.unshift(data);
    }
}
现在,这里是父组件
import {Component} from '@angular/core';
import {SharedService} from './shared.service';
import {ChildComponent} from './child.component';
import {ChildSiblingComponent} from './child-sibling.component';
@Component({
    selector: 'parent-component',
    template: `
        <h1>Parent</h1>
        <div>
            <child-component></child-component>
            <child-sibling-component></child-sibling-component>
        </div>
    `,
    providers: [SharedService],
    directives: [ChildComponent, ChildSiblingComponent]
})
export class parentComponent{
} 
和它的两个孩子
儿童 1
import {Component, OnInit} from '@angular/core';
import {SharedService} from './shared.service'
@Component({
    selector: 'child-component',
    template: `
        <h1>I am a child</h1>
        <div>
            <ul *ngFor="#data in data">
                <li>{{data}}</li>
            </ul>
        </div>
    `
})
export class ChildComponent implements OnInit{
    data: string[] = [];
    constructor(
        private _sharedService: SharedService) { }
    ngOnInit():any {
        this.data = this._sharedService.dataArray;
    }
}
孩子 2 (它是兄弟姐妹)
import {Component} from 'angular2/core';
import {SharedService} from './shared.service'
@Component({
    selector: 'child-sibling-component',
    template: `
        <h1>I am a child</h1>
        <input type="text" [(ngModel)]="data"/>
        <button (click)="addData()"></button>
    `
})
export class ChildSiblingComponent{
    data: string = 'Testing data';
    constructor(
        private _sharedService: SharedService){}
    addData(){
        this._sharedService.insertData(this.data);
        this.data = '';
    }
}
现在:使用此方法时要注意的事项。
- 在 PARENT 组件中仅包括共享服务的服务提供程序,而不包括子组件。
- 您仍然必须包含构造函数并将服务导入到子级中
- 这个答案最初是针对早期的Angular 2 beta版本回答的。所有已更改的都是 import 语句,因此,如果您偶然使用了原始版本,则只需更新即可。