Angular 2组件构造函数与OnInit [英] Angular 2 Component Constructor Vs OnInit

查看:353
本文介绍了Angular 2组件构造函数与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?

推荐答案

构造函数是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之间的区别

For more detail see also Difference between Constructor and ngOnInit

这篇关于Angular 2组件构造函数与OnInit的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆