Angular 如何将数据传递给精确的同级组件?
我有三个同级组件,它们使用相同的组件填充,如下所示Angular 如何将数据传递给精确的同级组件?,angular,typescript,Angular,Typescript,我有三个同级组件,它们使用相同的组件填充,如下所示 <div *ngIf="unitLevel && tribeLevel && squadLevel"> <at-unit-search [level]="unitLevel"></at-unit-search> <at-unit-search [level]="tribeLevel"></at-unit-search>
<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>
这是因为所有三个组件都是从同一个基本组件生成的。由于每个组件都有getArray()
方法,该方法在ngOnInit()
内部调用,因此当数据从特定组件发送时,所有三个组件都会接收该数据
是否有任何方法可以唯一地将数据发送到所需的组件
提前感谢。嘿,您可以在globle服务中为此定义全局变量
//assuming that senUnitService is a global service.
this.sendUnitService.unitLevel = unitLevel;
this.sendUnitService.tribeLevel= tribeLevel;
this.sendUnitService.squadLevel= squadLevel;
//and if then in the sibling component
this.unitLevel = this.sendUnitService.unitLevel;
this.tribeLevel = this.sendUnitService.tribeLevel;
this.squadLevel = this.sendUnitService.squadLevel;
大家好,欢迎来到StackOverflow 有不同的可能解决方案,但它们取决于您的需要 如果第三个孩子“始终”是唯一对通知感兴趣的孩子,我将传递一个输入
<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" handleNotification="true"></at-unit-search>
</div>
如果有一种方法可以过滤由sendUnitService
发出的数据,则可以使用
this.sendUnitService.getArray().pipe(
filter(x => .....),
....
).subscribe(units => {
this.operationalUnits = units
});
如果这两种方法都不适合您的需要,我会在服务中添加一些登录,以便允许组件的实例“注册”到特定的通知
请注意,最好有一个最小的运行示例(我建议使用)您可以首先将数据发送到父组件,然后父组件将该数据发送到特定组件。也可以使用BehaviorSubject发布和订阅数据。
if(this.handleNotification) {
this.sendUnitService.getArray().subscribe(units => {
this.operationalUnits = units
});
}
this.sendUnitService.getArray().pipe(
filter(x => .....),
....
).subscribe(units => {
this.operationalUnits = units
});