简体   繁体   English

我不明白为什么 Angular 组件 class 添加实现 onInit 接口

[英]I can't figure out why Angular component class add implements onInit interface

When you create a component through the "ng g component ~" command, the component class automatically implements 'OnInit' interface.通过“ng g component ~”命令创建组件时,组件class会自动实现'OnInit'接口。

The following snippet shows how a component can implement this interface to define its own initialization method.下面的代码片段展示了一个组件如何实现这个接口来定义它自己的初始化方法。

@Component({selector: 'my-cmp', template: `...`})
class MyComponent implements OnInit {
  ngOnInit() {
    // ...
  }
}

In the Angular documentation above, it says that the interface is meant to define its own initialization method,在上面的 Angular 文档中,它说接口是为了定义自己的初始化方法,

Even if you omit the 'implement OnInit' syntax, there is no problem in defining it through the ngOnInit () {} syntax.即使省略 'implement OnInit' 语法,通过 ngOnInit () {} 语法定义它也没有问题。

I am not sure why I have to write it.我不知道为什么我必须写它。

An interface (similar to java) is a contract between a component and an interface implementation.接口(类似于java)是组件和接口实现之间的契约。 Angular developer push to use OnInit like initialization block (and not the component constructor). Angular 开发人员推动使用OnInit之类的初始化块(而不是组件构造函数)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何呈现实现接口的组件? - How can I render a component that implements an interface? 执行任务的角度函数我无法弄清楚为什么它是这个函数 - Angular function that does task I can not figure out why it is this function 无法在Angular构造函数或OnInit中放置断点 - Can't put a breakpoint in Angular constructor or OnInit 如果不是绝对必要的,我应该删除 Angular CLI 创建组件时生成的 OnInit 实现吗? - Should I remove the OnInit implementation which is generated when a component is created by the Angular CLI if it isn't strictly necessary? 无法弄清楚为什么路由不起作用 - Can´t figure out why routing is not working Chrome 开发工具可以帮助找出 Angular 组件名称吗? - Can Chrome Dev tools help figure out Angular component name? Angular - 找出派生的 class 是否实现了抽象 class (router.component) - Angular - find out if derived class implements an abstract class (router.component) 无法弄清楚为什么res.json()没有在单元测试覆盖率Angular中命中 - Can't figure out why res.json() is not hit in Unit Test Coverage, Angular 如何在不出错的情况下实现 OnInit:Class 正在使用 Angular 功能但未进行装饰。 请添加显式 Angular 装饰器 - How do I implement OnInit without getting error: Class is using Angular features but is not decorated. Please add an explicit Angular decorator 您可以在实现另一个接口的组件的接口中键入字段吗? - Can you type a field in an interface to a Component that implements another interface?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM