首页 > 解决方案 > Angular 子组件未检测到更改

问题描述

我正在从父组件更新产品对象。不知何故,子组件没有检测到更改并且没有更新它。

产品.ts

export interface Product { 
    productId: number;
    productName: string;
    lastUpdated: string;
    orders: Array<Order>
}

订单.ts:

export interface Order { 
    orderId: number;
    payments: Array<Payment>
}

付款.ts:

export interface Payment { 
    paymentId: number;
    amount: Array<number>
}

父组件.html

<product-details [(product)]="product1" (refreshProduct)="refreshProduct()"></product-details>

父组件.ts

product1: Product = null;

refreshProduct() {
      this.sub = this.productService.getTheLatestOrders().subscribe(
        (data) => {
          this.product1.lastUpdated = data.lastUpdated;
          this.product1.orders.forEach(order => {
            let latestOrderData = data.orders.find(d => d.orderId == order.orderId);
            if(latestOrderData) {
              order.payments = latestOrderData.payments;
            }
          });
          // this.product1 = JSON.parse(JSON.stringify(this.product1)); --> It works if I add this
      });
    }
  }

product-details.component.html(子组件)

<button id="refresh" name="refresh" (click)="refresh()" />
Last Updated : {{product.lastUpdated}}

<ng-container *ngFor="let order of product.orders">
      <ng-container *ngFor="let payment of order.payments">
             {{payment.date}} - {{payment.amount}} 
      </ng-container>
</ng-container>

product-details.component.ts(子组件)

@Input('product') product: Product;
@Output() refreshProduct = new EventEmitter<any>();

refresh() {
  this.refreshProduct.emit();
}

我试图changeDetection: ChangeDetectionStrategy.Default明确声明,但没有运气。

如代码中所述,如果我添加,JSON.parse(JSON.stringify(this.product1));则它可以工作。所以看来我需要创建一个新对象以便更改检测工作。我想我可以使用扩展运算符(object.assign)来确保它创建一个新对象。但是,我不确定如何使用扩展操作更新 refreshProduct() 方法中的产品。

我认为代码将如下所示:

this.product1 = {...this.product1, 
            lastUpdated: data.lastUpdated,
            orders: .... // --> Not sure how to loop through orders and update the payments

          };

编辑:我想我设法做到了。

this.product1 = {...this.product1, 
            lastUpdated: data.lastUpdated,
            orders: this.product1.orders.map((order) => {
                     let updatedOrder = data.orders.find(o => o.orderId == order.orderId);  
                     return {...order, order.payments: updateOrder.payments};

                    })
          };

如果有更好的解决方案,请告诉我。

标签: javascriptangulartypescriptangular-changedetection

解决方案


尝试这样做:

refreshProduct() {
      let temp: Product = {};
      this.sub = this.productService.getTheLatestOrders().subscribe(
        (data) => {
          temp.lastUpdated = data.lastUpdated;
          temp.orders.forEach(order => {
            let latestOrderData = data.orders.find(d => d.orderId == order.orderId);
            if(latestOrderData) {
              order.payments = latestOrderData.payments;
            }
          });
          this.product1 = temp;
      });
    }
  }

这样每次它都会将更新的值分配给产品。


推荐阅读