我正在通过ngFor循环呈现一些动态组件,我希望这些组件能够相互通信。我这样做的第一个想法是订阅一些来自助手状态服务(myComunicationService)的Subject更改:
<div *ngFor="let entry of dataList">
<custom-component [entry]="entry"/>
</div>自定义组件ts
export class CustomComponent implements OnInit {
@Input() entry: Entry;
private subscriptions: Subscription = new Subscription();
constructor(private myComunicationService: MyComunicationService) {}
public ngOnDestroy(): void {
this.subscriptions.unsubsribe();
}
public ngOnInit(): void {
this.subscriptions.add(
this.myComunicationService.dataChanged$.subscribe(
(dataChanged) => {
if (isForThisComponentInstance(dataChanged)) {
// do stuff for this component instance only
}
}
);
);
}
// private isForThisComponentInstance = (dataChanged) => boolean
// this method checks some unique property that matches with the instance component
}基本上,我的所有组件都在侦听同一个事件,所有组件都在捕捉该事件,而if { }语句是某种过滤器,它实际上允许组件更改/执行一些事情。(对这种方法不太满意)
我如何改进这一点而不依赖于if语句?
发布于 2020-09-29 20:25:05
而不是使用
this.myComunicationService.dataChanged$直接在您的组件中,您可以要求服务为您做一些额外的工作。
说this.myComunicationService.getChangesFor(this)
然后为你服务
getChangesFor(compy: CustomComponent): Observable<any>{
return this.dataChanged$.pipe(
filter(data => data.id === compy.id)
);
}这实际上是一回事,但是在逻辑从组件中删除之后,它可能并不真正属于组件。这样,如果10个不同的组件都调用此服务,它们并不都分别实现此逻辑。它还提供了改变通信服务处理问题的方式的自由。
例如:
然而,在某种程度上,数据流向的逻辑取决于你。
https://stackoverflow.com/questions/64115400
复制相似问题