更新到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); }}现在,这里是PARENT组件
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语句,所以如果你偶然使用了原始版本,则只需更新即可。



