加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angular2 – 构造函数和ngOnInit之间的差异

发布时间:2020-12-17 09:14:08 所属栏目:安全 来源:网络整理
导读:默认情况下,Angular 2提供生命周期钩子ngOnInit。如果我们已经有一个构造函数,任何人都可以告诉我关于ngOnInit的用法? Constructor是类实例化时执行的类的默认方法,并确保正确初始化类及其子类中的字段。角度或更好的DI分析构造函数参数,当它通过调用新
默认情况下,Angular 2提供生命周期钩子ngOnInit。如果我们已经有一个构造函数,任何人都可以告诉我关于ngOnInit的用法?
Constructor是类实例化时执行的类的默认方法,并确保正确初始化类及其子类中的字段。角度或更好的DI分析构造函数参数,当它通过调用新的MyClass()创建一个新的实例时,它试图找到匹配构造函数参数类型的提供者,解析它们并将它们传递给构造函数
new MyClass(someArg);

ngOnInit是一个由Angular2调用的生命周期钩子,用于指示Angular是创建组件的。

我们必须导入OnInit为了像这样使用(实际上实现OnInit不是强制性的,但被认为是良好的做法):

import {Component,OnInit} from 'angular2/core';

然后使用OnInit的方法,我们必须在类中实现这样。

export class App implements OnInit{
  constructor(){
     //called first time before the ngOnInit()
  }

  ngOnInit(){
     //called after the constructor and called  after the first ngOnChanges() 
  }
}

Implement this interface to execute custom initialization logic after your directive’s data-bound properties have been initialized.
ngOnInit is called right after the directive’s data-bound properties have been checked for the first time,
and before any of its children have been checked.
It is invoked only once when the directive is instantiated.

大多数情况下,我们使用ngOnInit来初始化/减速,避免在构造函数中工作。构造函数应该只用于初始化类成员,但不应该做实际的“工作”。

所以你应该使用constructor()来设置依赖注入,而不是其他的。 ngOnInit()是“start”的更好的地方 – 它是在哪里/当组件的绑定被解决

更多信息请参考这里

> https://angular.io/docs/js/latest/api/core/index/OnInit-class.html
> Angular 2 Component Constructor Vs OnInit

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读