Angular 2 组件构造函数与 OnInit [英] Angular 2 Component Constructor Vs OnInit
问题描述
如果我希望每次加载组件时函数 x 都发生,无论是第一次,我导航到不同的站点并返回,或者是组件第五次加载.
If I want function x to happen every time a component loads, whether its the first time, I navigate to a different site and navigate back or it's the fifth time the component has loaded.
我应该把函数 x 放在什么地方?组件构造函数还是OnInit?
What should I put function x in? The component constructor or OnInit?
推荐答案
Constructor 是 typescript 类的预定义默认方法.Angular 和 constructor
之间没有关系.通常我们使用 constructor
来定义/初始化一些变量,但是当我们有与 Angular 绑定相关的任务时,我们会转到 Angular 的 ngOnInit
生命周期钩子.ngOnInit
在构造函数调用之后被调用.我们也可以在构造函数中做同样的工作,但最好使用 ngOnInit
来启动 Angular 的绑定.
Constructor is predefined default method of the typescript class. There is no relation between Angular and constructor
. Normally we use constructor
to define/initialize some variables, but when we have tasks related to Angular's bindings we move to Angular's ngOnInit
life cycle hook. ngOnInit
is called just after the constructor call. We can also do the same work in the constructor but its preferable to use ngOnInit
to start Angular's binding.
为了使用 ngOnInit
我们必须从核心库中导入这个钩子:
in order to use ngOnInit
we have to import this hook from the core library:
import {Component, OnInit} from '@angular/core'
然后我们用导出的类来实现这个接口(这不是实现这个接口的强制性要求,但通常我们会这样做).
Then we implement this interface with exported class (this is not compulsory to implement this interface but generally we did).
使用两者的示例:
export class App implements OnInit{
constructor(){
//called first time before the ngOnInit()
}
ngOnInit(){
//called after the constructor and called after the first ngOnChanges()
}
}
更多细节参见构造函数和ngOnInit的区别
这篇关于Angular 2 组件构造函数与 OnInit的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!