【发布时间】:2019-11-21 04:58:38
【问题描述】:
我有三个同级组件,它们使用以下相同的组件填充。
<div *ngIf="unitLevel && tribeLevel && squadLevel">
<at-unit-search [level]="unitLevel"></at-unit-search>
<at-unit-search [level]="tribeLevel"></at-unit-search>
<at-unit-search [level]="squadLevel"></at-unit-search>
</div>
我需要将一些数据从第一个兄弟姐妹传递给第三个兄弟姐妹,而不是第二个兄弟姐妹。我为此使用了服务。但它会将数据发送到所有三个组件。
单元搜索组件的打字稿
export class UnitSearchComponent implements OnInit {
operationalUnits: OperationalUnitLightWeight[];
previousTimeAllSelected: boolean;
@ViewChild('allSelected', { static: false }) private allSelected: MatOption;
@Input() level: any;
unitForm = new FormGroup({ unitControl: new FormControl('') });
childUnits : any[];
constructor(private commonServerService: CommonServerService,private sendUnitService: UnitService ) {
this.childUnits=[];
}
ngOnInit() {
this.commonServerService.findOperationalUnitsByLevelId(this.level.id).subscribe(operationalUnits => {
{
this.operationalUnits = operationalUnits;
this.operationalUnits.sort((a , b) => a.name.localeCompare(b.name));
}
});
this.sendUnitService.getArray().subscribe(units => {
this.operationalUnits = units
});
}
optionChange() {
this.unitForm.controls.unitControl.value.forEach(id => {
{
if (id === 0) {
this.previousTimeAllSelected = true;
}
}
});
let selectedUnitIds = this.toggleAllSelection();
this.getChildUnits(selectedUnitIds);
}
getChildUnits(selectedUnitIds: any[]) {
let children= this.loadChildUnits(selectedUnitIds);
this.sendUnitService.sendArray(children);
}
这是因为所有三个组件都是从同一个基础组件生成的。由于每个组件都有在ngOnInit() 内部调用的getArray() 方法,因此当从特定组件发送数据时,所有三个组件都在接收该数据。
有什么方法可以唯一地将数据发送到只需要的组件?
提前致谢。
【问题讨论】:
-
您可以先将数据发送到父组件,然后父组件会将数据发送到特定组件。或者您可以使用 BehaviorSubject 发布和订阅数据。
标签: angular typescript