【发布时间】:2020-11-19 00:46:29
【问题描述】:
在通过 subscribe 方法在父组件中操作数据后,ngOnChanges 没有被子组件触发。
基本上我的主要组件是这样的:
public imageGroups: IImageGroup[];
public status$: Observable<ModelStatusesModel>;
public ngOnChanges(changes: SimpleChanges): void {
if (Boolean(this.treeData)) {
this.imageGroups = this.treeDataService.convertImageGroups(this.treeData);
this.status$ = this.updateStatus();
this.status$.subscribe((status: ModelStatusesModel) => {
this.treeDataService.updateStatus(this.imageGroups, status); // this function makes changes to this.imageGroups
console.log('subscribe happened');
});
}
}
HTML:
...
<ul class="treeview-nodes-wrapper">
<treeview-branch *ngFor="let group of (imageGroups)"
[group]="group"></treeview-branch>
</ul>
...
分支也有 ngOnChnages:
public ngOnChanges(): void {
this._currentNodeDisabled = this.group.isDisabled;
console.log(this.group); //returns isDisables as true
console.log(this.group.isDisabled); //returns false
console.log(this._currentNodeDisabled); //returns false
}
当我运行我的应用程序时,这是控制台中的结果:
{ ... isDisabled: true ...},
false
false
subscribe happened
我还试图在我的订阅中将呼叫包围在 ngZone.run 中,但没有任何成功。你知道如何告诉 Angular 触发了孩子中的ngOnChanges 吗?
编辑: 对我有用的是在父组件 (public change = false;) 中创建一个属性,然后在我的 subscribe 方法中切换此属性并将其作为我的子元素的输入。这被认为是一种改变。尽管这解决了我的问题,但它看起来更像是一种非常 hacky 的代码编写方式。
【问题讨论】:
-
@MarcHernández 我看不出这将如何应用于我的问题,因为我正在处理一个非常不同的结构
标签: javascript angular ngrx angular2-observables ngonchanges