实施 ngOnChange 以捕获 Angular2 中的旧值和当前值

Implementing ngOnChange to capture old and current value in Angular2

我试图实现 ngOnChanges() 来捕获以前和当前的值。我实现的功能工作正常。我能够在控制台中看到以前和当前的值,但即使我的代码编译成功,我也会收到此错误。 "propertyName"、"change"、"current" 和 "previous" 出现相同的错误。如果我使用 'const' 而不是 'let' 那么我的函数就不起作用了。请帮忙!!

代码:

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

@Component({
selector: 'app-simple',
templateUrl: './simple.component.html'
})
export class SimpleComponent implements OnChanges {
  @Input() simpleInput: string;

  ngOnChanges(changes: SimpleChanges) {
    for (let propertyName in changes) {
    let change = changes[propertyName];
    let current = JSON.stringify(change.currentValue);
    let previous = JSON.stringify(change.previousValue);
    console.log(propertyName + ' : currentvalue ' + current + ', previousvalue ' + previous);
    }
  }
}

还有另一种迭代数组的方法。在高级 for 循环中使用 of。 尝试使用 for (let propertyName of changes){} 这可能对你有帮助。

编辑1: 如果永远不会重新分配变量,则使用 const 声明更好。 https://eslint.org/docs/rules/prefer-const 像这样尝试:

ngOnChanges(changes: SimpleChanges) {
for (const propertyName in changes) {
  if (changes[propertyName]) {
    const change = changes[propertyName];
    const current = JSON.stringify(change.currentValue);
    const previous = JSON.stringify(change.previousValue);
    console.log(propertyName + ' : currentvalue ' + current + ', previousvalue ' + previous);
  }

} }

这是一个 ESlint 错误:https://eslint.org/docs/rules/prefer-const

您的代码 工作正常,因为它在编程上没有任何问题,只是不利于可读性,如我提供的 link 中所述。如果您不想看到错误,可以在 tslint.json 文件中将其禁用。您可以手动执行此操作,也可以使用错误对话框中的第三个选项,即 'Remove rule prefer-const from tslint.json'.