【问题标题】:Component nested in more component not lose reference in change component嵌套在更多组件中的组件不会在更改组件中丢失参考
【发布时间】:2020-06-29 13:10:29
【问题描述】:

我有 2 个带有嵌套其他组件的组件:

  • BacklogComponent
...
<backlog-table>
  <ng-container expandedDetail>
    <manual-amount [maxValueFunction]="maxValue()"></manual-amount>
   </ng-container>
</backlog-table>
...
maxValue() {
  return (entity) => {
    console.log(this); // added for debug
    return subNumbers(entity.financeable, entity.financed);
  };
}
  • CollectionComponent
...
<receivable-table>
  <ng-container expandedDetail>
    <manual-amount [maxValueFunction]="maxValue()"></manual-amount>
   </ng-container>
</receivable-table>
...
maxValue() {
  return (entity) => {
    return reconcileElement(entity.outstanding, entity.collected, entity.amount, entity.total);
  };
}

ReceivableTableComponentBacklogTableComponent 具有相同的模板

...
<ng-content select="[expandedDetail]"></ng-content>
...

ManualAmountComponent implements OnInit 和:

ngOnInit() {
  this.expandedDetailService.entity$
  .subscribe((gotEntity: T) => {
    if (gotEntity) {
      this.element = gotEntity;
      this.maxValue = this.maxValueFunction(this.element);
    }
  });
}

现在,启动应用程序,我转到CollectionComponent 的链接并在控制台中有

CollectionComponent {...}

然后我更改页面并转到BacklogComponent。在控制台中添加

CollectionComponent {...}

BacklogComponent{...}

为什么我的组件CollectionComponent 没有销毁?不,我将ngOnDestroy 添加到CollectionComponent 并且当我更改页面时调用它,但是为什么ManualAmountComponent 在我调用BacklogComponent 时引用CollectionComponent? (显然,如果我在控制台中做相反的事情

BacklogComponent{...}

BacklogComponent{...}

CollectionComponent {...})

【问题讨论】:

    标签: angular


    【解决方案1】:

    因为您在两个父组件中使用相同的组件。 它将具有引用,因为它在整个应用程序中保持循环。

    如果您想释放先前绑定组件的引用,您需要使用ManualAmountComponent 中的ngOnDestroy 方法来重置您想要重新初始化的所有值。

    当您在ManualAmountComponent 订阅服务时,您还需要unsubscribe() 它。

    所以你需要在嵌套组件中维护订阅数组,如下所示。

     subscriptions:Subscription[]=[]       
     ngOnInit() {
          this.subscriptions.push(this.expandedDetailService.entity$
          .subscribe((gotEntity: T) => {
            if (gotEntity) {
              this.element = gotEntity;
              this.maxValue = this.maxValueFunction(this.element);
            }
          });
         ) 
        }
     ngOnDestroy(){
      this.subscriptions.forEach((subscription)=>subscription.unSubscribe())
    }
    

    【讨论】:

    • 如果这解决了问题,请验证并投票,以便其他人可以使用。
    猜你喜欢
    • 1970-01-01
    • 2019-01-03
    • 1970-01-01
    • 2018-01-15
    • 2017-12-31
    • 2021-04-25
    • 2023-01-16
    • 2018-10-28
    • 1970-01-01
    相关资源
    最近更新 更多