【问题标题】:Angular life-cycle events call without implementing interface?Angular生命周期事件调用而不实现接口?
【发布时间】:2021-02-25 00:22:56
【问题描述】:

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

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

生命周期.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!');
  }
}

生命周期.component.html

<p>
  life-cycle works!
</p>

【问题讨论】:

  • 谁反对我的问题?发表评论并投反对票。
  • 接口是可选的。向 TypeScript 指令类添加接口是一种很好的做法,以便从强类型和编辑器工具中受益。

标签: angular typescript


【解决方案1】:

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

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

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

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

(感谢@Nick)

【讨论】:

  • 添加一点关于它们的优点.... 1) 它在类的开始就明确了要使用的生命周期钩子(如果类有,这并不总是很清楚)很多方法),2)如果您没有实现正确的方法,Typescript 会警告您(例如,忘记实现、拼错函数名或后来有人不小心删除了它)
  • 感谢@Nick,我在回答中添加了优势。
【解决方案2】:

在打字稿中,你不需要显式地实现一个接口来实现它。

看看下面这段代码:

export interface BaseModel {

   int myNumber;

}

export class SomeModel {

    int myNumber;

}

以下是完全正确的:

private myFunction(myModel: BaseModel) {
    // Do smthg
}

let johnDoe = new SomeModel();
myFunction(johnDoe); 

完全合法,因为类型检查不是基于正在实现的类,而是因为 BaseModel 的所有属性都包含在 SomeModel 中。

这有时被称为“鸭子类型”或“结构子类型”

https://www.typescriptlang.org/docs/handbook/interfaces.html

【讨论】:

    猜你喜欢
    • 2017-01-02
    • 2016-12-19
    • 2017-04-30
    • 2014-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多