简体   繁体   English

Angular 8+ - 如果我不打算覆盖它,是否需要在我的组件中实现 OnInit function?

[英]Angular 8+ - do I need to implement the OnInit function in my components if I am not planning to override it?

I'm working on a project with Angular 8.我正在使用 Angular 8 进行项目。

I noticed that when I generate components with the command line that they come with OnInit.我注意到,当我使用 OnInit 附带的命令行生成组件时。

eg例如

export class SideDrawerComponent implements OnInit {

    constructor(private sideDrawerService: SideDrawerService) { }

    public ngOnInit(): void { }

    public close() {
        this.sideDrawerService.closeDrawer();
    }

}

As I am not going to override the function, do I need it there?由于我不会覆盖 function,我需要它吗?

No. You can remove it and the OnInit interface.不,您可以删除它和 OnInit 接口。

From the docs :文档

The hooks give you the opportunity to act on a component or directive instance at the appropriate moment, as Angular creates, updates, or destroys that instance.当 Angular 创建、更新或销毁该实例时,这些钩子让您有机会在适当的时候对组件或指令实例进行操作。 If you implement this method in your component or directive class, Angular calls it shortly after checking the input properties for that component or directive for the first time.如果您在组件或指令 class 中实现此方法,则 Angular 在第一次检查该组件或指令的输入属性后不久将调用它。

So it isn't mandatory, but will be triggered if you include it.所以它不是强制性的,但如果你包含它就会被触发。

Also if you so wish to include a lifecycle hook (eg. ngOnInit ) then implementing the corresponding interface ( OnInit ) isn't mandatory.此外,如果您希望包含一个生命周期钩子(例如ngOnInit ),那么实现相应的接口( OnInit )不是强制性的。 The interface is only there to guide the users for type checks and typos.该界面仅用于指导用户进行类型检查和拼写错误。 In theory you could include all the lifecycle hook functions without implementing their interface counterparts.理论上,您可以包含所有生命周期钩子函数,而无需实现它们的接口对应项。

See here more info. 在这里查看更多信息。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM