【问题标题】:Angular ngOnChanges in child doesn't trigger after subscribe manipulates data订阅操作数据后,子项中的 Angular ngOnChanges 不会触发
【发布时间】: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 的代码编写方式。

【问题讨论】:

标签: javascript angular ngrx angular2-observables ngonchanges


【解决方案1】:

这是当输入值changes 时触发 ngOnChanges 的结果,并且对于通过引用传递的对象,对其属性的修改不会显式更改传递下来的内容。解决方案通常是执行克隆、...扩展运算符或重新分配给在父级 [input] 中传递的属性。

您将附加输入更改为新值以触发 ngOnChanges 的解决方案也可以,这是一种解决方法,但那是 Web 开发。请记住,如果您将属性设置为 true,然后再次设置为 true,它将不会触发,因此计数变量可能会更好地工作(这有点 hacky)。

【讨论】:

    【解决方案2】:

    通过 JSON.parse 进行克隆比切换变量更简洁地解决了我的问题:

    ...
      this.status$.subscribe((status: ModelStatusesModel) => {
        this.treeDataService.updateStatus(this.imageGroups, status);
        triggerChange();
      });
    ...
    
    private triggerChange() {
        this.imageGroups = JSON.parse(JSON.stringify(this.imageGroups));
    }
    

    【讨论】:

      猜你喜欢
      • 2020-11-15
      • 1970-01-01
      • 2017-11-29
      • 2018-06-21
      • 1970-01-01
      • 2022-07-11
      • 2019-04-21
      • 1970-01-01
      • 2021-04-24
      相关资源
      最近更新 更多