我试图实现角度生命周期挂钩,并且我不断收到与角度生命周期实现界面相关的这些错误。
Class' LifecycleComponent'错误地实现了界面' DoCheck'。
这是我的组件代码。
import { Component, OnInit, OnChanges, OnDestroy, DoCheck, AfterContentChecked, AfterContentInit } from '@angular/core';
@Component({
selector: 'app-lifecycle',
templateUrl: './lifecycle.component.html',
styleUrls: ['./lifecycle.component.css']
})
export class LifecycleComponent implements OnInit, OnChanges, OnDestroy, DoCheck, AfterContentChecked, AfterContentInit {
dataOnInit = 0;
dataOnChanges = 0;
dataOnDestroy = 0;
dataDoCheck = 0;
dataAfterContentChecked = 0;
dataAfterContentInit = 0;
constructor() { }
OnInit(): void {
this.dataOnInit += 1;
console.log(`OnInit called ${this.dataOnInit} times!`);
}
OnChanges(): void {
this.dataOnChanges += 1;
console.log(`OnChanges called ${this.dataOnChanges} times!`);
}
Destroy(): void {
this.dataOnDestroy += 1;
console.log(`OnDestroy called ${this.dataOnDestroy} times!`);
}
DoCheck(): void {
this.dataDoCheck += 1;
console.log(`DoCheck called ${this.dataDoCheck} times!`);
}
AfterContentChecked(): void {
this.dataAfterContentChecked += 1;
console.log(`AfterContentChecked called ${this.dataAfterContentChecked} times!`);
}
AfterContentInit(): void {
this.dataAfterContentInit += 1;
console.log(`AfterContentInit called ${this.dataAfterContentInit} times!`);
}
答案 0 :(得分:0)
显然,这里的错误是如何调用这些事件的。导入的名称不能直接用作事件功能。 E.g。
DoCheck(): void { console.log('DoCheck'); } // this is incorrect!
您应该在调用这些角度生命周期事件时添加ng
前缀。 E.g。
ngDoCheck(): void { console.log('DoCheck'); }