角度生命周期事件调用没有实现接口?

baj*_*032 1 typescript angular

我正在使用角度应用程序,我发现角度生命周期事件是没有实现接口的调用.在下面的例子中,如果我从组件中删除接口,那么所有角度生命周期钩子都正常工作.关于没有实现接口的问题,为什么angular会调用所有事件?

我知道在typescript中我们可以使用我们可以用于c#的所有OOP概念.

生命cycle.component.ts

import {
  Component,
  OnInit,
  OnChanges,
  SimpleChanges,
  Input,
  AfterViewInit,
  DoCheck,
  AfterViewChecked,
  AfterContentChecked,
  AfterContentInit,
  OnDestroy
} from '@angular/core';

@Component({
  selector: 'app-life-cycle',
  templateUrl: './life-cycle.component.html',
  styleUrls: ['./life-cycle.component.css']
})
export class LifeCycleComponent
  implements
    OnChanges,
    OnInit,
    DoCheck,
    AfterViewInit,
    AfterViewChecked,
    AfterContentChecked,
    AfterContentInit,
    OnDestroy {
  @Input('appTitle') appTitle: string;
  constructor() {
    console.log('constructor called!');
  }

  ngOnChanges(changes: SimpleChanges) {
    console.log('ngOnChanges called!');
    console.log(changes);
  }
  ngOnInit() {
    console.log('ngOnInit called!');
  }

  ngDoCheck() {
    console.log('ngDoCheck called!');
  }

  ngAfterViewInit() {
    console.log('ngAfterViewInit called!');
  }
  ngAfterViewChecked() {
    console.log('ngAfterViewChecked called!');
  }
  ngAfterContentInit() {
    console.log('ngAfterContentInit called!');
  }
  ngAfterContentChecked() {
    console.log('ngAfterContentChecked called!');
  }
  ngOnDestroy() {
    //console.log('ngOnDestroy called!');
  }
}
Run Code Online (Sandbox Code Playgroud)

生命cycle.component.html

<p>
  life-cycle works!
</p>
Run Code Online (Sandbox Code Playgroud)

JSO*_*ulo 6

Angular生命周期接口的使用是可选的.他们只是作为开发人员帮助您.

从技术上讲,TypeScript被编译为JavaScript,它没有接口.Angular只调用JavaScript生命周期方法(如果存在).这就是为什么如果你使用接口它没有任何区别的原因.(来源:文件)

不过,您应该使用这些接口有多种原因:

  1. 更清楚的是实际使用了哪些Lifecycle事件.在具有许多方法的大班级中,您很快就会失去概述.使用这些接口可以在一个地方快速确定所有使用过的生命周期方法 - 在TypeScript类的开头.
  2. 如果您没有正确实现Lifecycle方法,TypeScript编译器会发出警告,例如,如果您忘记实现方法,拼写错误的方法名称或意外删除方法.

(@Nick的积分)