更新到rc.4: 當試圖獲得角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(這是西布林g)
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組件中的共享服務的服務提供者而不包含子對象的服務提供者。
- 您還必須包含構造函數並將服務導入到子項中
- 此答案最初是爲早期角度2測試版本回答的。所有改變的都是導入語句,所以如果你偶然使用原始版本,就需要更新。
你有沒有找到任何方式爲兄弟姐妹數據共享?我需要它作爲可觀察的.. –
你找到它的解決方案,我也需要這個 –