微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Angular和NGXS商店应用程序在商店更新中循环结束

如何解决Angular和NGXS商店应用程序在商店更新中循环结束

我使用NGXS作为存储机制。在商店中,有一个条件列表,这些条件通过UI上的RuleEngineAddViewStepperConditionComponent显示*ngFor中。因此,每个条件都有自己的RuleEngineAddViewStepperConditionListCardComponent

每个条件都包含诸如Selecttargettype之类的设置。这些设置每个都在一个额外的组件中实现,例如在RuleEngineAddViewStepperConditionListCardSelecttargettypeComponent中。如果用户现在更改设置,则此设置将更改并通过分派保存在商店中。通过更改StoreModel,* ngFor再次由Observable触发,后者也触发ngOnInit,这会导致带有以下错误的循环。如何更改设置,以便更新列表,但不会引发错误

enter image description here

RuleEngineAddViewStepperConditionComponent

<div *ngFor="let condition of (conditions$ | async)">
  <app-rule-engine-add-view-stepper-condition-list-card [conditionId]="condition.conditionId">
  </app-rule-engine-add-view-stepper-condition-list-card>
</div>

export class RuleEngineAddViewStepperConditionComponent {
  ...
  @Select(RuleEnginestate.getConditions)
  public conditions$: Observable<RuleCondition[]>;
  ...
}

RuleEngineAddViewStepperConditionListCardComponent

<app-rule-engine-add-view-stepper-condition-list-card-select-target-type [conditionId]="conditionId">
</app-rule-engine-add-view-stepper-condition-list-card-select-target-type>

RuleEngineAddViewStepperConditionListCardSelecttargettypeComponent

<mat-form-field [formGroup]="form">
  ...
</mat-form-field>

export class RuleEngineAddViewStepperConditionListCardSelecttargettypeComponent implements OnInit {
  ...
  public ngOnInit(): void {
    this.ruleId = this.store.selectSnapshot(RuleEnginestate.getSelectedRuleId);
  }

  private onFormChanges(): void {
    this.form.valueChanges.subscribe(val => {
       const targettype: RuleConditiontargettype = val.targettype;
       if (targettype) {
         this.store.dispatch(new RuleEngineConditionAddtargettypeAction(this.ruleId,this.conditionId,targettype));
       }
    });
  }
  ...
}

解决方法

我找到了一个有用的解决方案。我使用TrackBy阻止呈现完整列表,现在我仅呈现新添加的元素。

https://dzone.com/articles/how-to-use-trackby-with-ngfor-in-angular-8

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。