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

前端之家收集整理的这篇文章主要介绍了angular2 – 构造函数和ngOnInit之间的差异前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
默认情况下,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

原文链接:https://www.f2er.com/angularjs/147182.html

猜你在找的Angularjs相关文章