簡體   English   中英

應為方法 ngOnChanges 實現 Angular 生命周期接口 OnChanges

[英]Angular Lifecycle Interface OnChanges should be implemented for method ngOnChanges

Tslint 正在發送警告,指示應為方法ngOnChagnes生命周期掛鈎實現OnChanges 如果我將ngOnChanges更改為OnChanges則警告不存在。

import { Component, Input, OnInit, Output, EventEmitter, SimpleChange, OnChanges } from '@angular/core';

import { Order } from '../../../../core/orders';

import { CartItem } from '../../../../core/orders';
import { User } from '../../../../core/auth/_models/user.model';

declare var $: any;

@Component({
  selector: 'app-order-summary',
  templateUrl: './order-summary.component.html',
  styleUrls: ['./order-summary.component.scss']
})
export class OrderSummaryComponent implements OnInit, OnChanges {
  @Input() cartDetails: Order;
  @Input() sellerDetail: User;
  @Input() productCost: number;
  @Output() closeOrderSummary = new EventEmitter<string>();
  @Output() checkoutCart = new EventEmitter<string>();
  @Output() updateItemQty = new EventEmitter<string>();
  @Output() updateProductSelected = new EventEmitter<string>();

  cartList: CartItem[] = [];
  isCartEmpty: boolean;

  constructor() {}

  ngOnChanges(changes: SimpleChange) {
    for (const propName in changes) {
      if (propName === 'cartDetails') {
        const change = changes[propName];
        this.cartList = change.currentValue;
        this.isCartEmpty = (change.currentValue.length === 0);
      }
    }
  }

  ngOnInit(): void {
  }

  onUpdateItemCount(item, direc) {
    const payload = { item, direc };
    this.updateItemQty.emit(payload);
  }

  onUpdateProductSelected(value, item) {
    const payload = { value, item};
    this.updateProductSelected.emit(payload);
  }

  goBackToMain() {
    this.closeOrderSummary.emit();
  }

  onCheckoutCart() {
    this.checkoutCart.emit();
  }

}


 
implements OnInit, OnChanges

不見了。 每當您使用 Angular 生命周期鈎子時,您還應該向控制器類添加相應的實現接口。

OnChanges接口中聲明的ngOnChanges()函數的參數接受類型為SimpleChanges而不是SimpleChange參數。 正如其他答案的評論中所提到的,在不實現OnChanges接口的情況下使用函數ngOnChanges()也將被 Angular 接受為生命周期鈎子。 但是您收到的類型錯誤不會被拋出,這可能會導致其他問題。

import { Component, Input, OnInit, Output, EventEmitter, SimpleChanges, OnChanges } from '@angular/core';

ngOnChanges(changes: SimpleChanges) {
  ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM