Angular生命周期接口OnChanges应该为ngOnChanges方法实现



Tslint正在发送一个警告,表明OnChanges应该为方法ngOnChagnes的生命周期钩子实现。如果我将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生命周期钩子时,你还应该在控制器类中添加相应的implements接口。

OnChanges接口中声明的ngOnChanges()函数的参数接受SimpleChanges类型的参数,不接受SimpleChange类型的参数。正如在其他回答的评论中提到的,使用ngOnChanges()函数而不实现OnChanges接口也会被Angular接受为一个生命周期钩子。但是您收到的类型错误不会被抛出,否则可能会导致其他问题。

import { Component, Input, OnInit, Output, EventEmitter, SimpleChanges, OnChanges } from '@angular/core';
ngOnChanges(changes: SimpleChanges) {
...
}

相关内容

  • 没有找到相关文章

最新更新