Angular中constructor和ngOnInit适用场景的差异化

区别

constructor是类的自身属性,是在ES6引入类的概念后才出现的,其并不属于Angular的范畴,所以Angular没有办法控制constructor。constructor()会在angular所有的生命周期钩子之前被调用,它的重要作用是注入依赖 , 需要用到的一些依赖可以在此注入,便可以作为类的属性被使用!

例如:在当前组件注入ValidateService) 依赖,即为当前组件或者说一个实例添加了一个validateService: 属性,然后通过this.validateService来访问到该属性,
进而可以使用该属性中的方法和子属性

引入
import { ValidateService } from '../../tools/services/validate/validate.service';


像当前类注入依赖,即为当前类增加一个属性
constructor(public validateService: ValidateService) { }



通过this指向来获取该属性使用
ngOnInit() {
      console.log(this.validateService);
 }

constructor会在类生成实例时调用:

import {Component} from '@angular/core';

@Component({
    selector: 'hello-world',
    templateUrl: 'hello-world.html'
})

class HelloWorld {
    constructor() {
        console.log('constructor被调用,但和Angular无关');
    }
}

// 生成类实例,此时会调用constructor
new HelloWorld();

ngOnInit的官方的说法:

ngOnInit用于在Angular第一次显示数据绑定和设置指令/组件的输入属性之后,初始化指令/组件。

ngOnInit属于Angular生命周期的一部分,其在第一轮ngOnChanges完成之后调用,并且只调用一次;在构造函数constructor之后马上执行复杂的初始化逻辑,相当于通知开发者组件已经初始化完成,可以操作组件中的数据了

import {Component, OnInit} from '@angular/core';

@Component({
    selector: 'hello-world',
    templateUrl: 'hello-world.html'
})

class HelloWorld implements OnInit {
    constructor() {

    }

    ngOnInit() {
        console.log('ngOnInit被Angular调用');
    }
}

constructor适用场景

其主要作用是注入依赖,特别是在TypeScript开发Angular工程时,经常会遇到类似下面的代码:

import { Component, ElementRef } from '@angular/core';

@Component({
    selector: 'hello-world',
    templateUrl: 'hello-world.html'
})
class HelloWorld {
    constructor(private elementRef: ElementRef) {
        // 在类中就可以使用this.elementRef了
    }
}

constructor中注入的依赖,就可以作为类的属性被使用了。

ngOnInit适用场景

ngOnInit的主要作用就是通知开发者此时组件/指令上的属性绑定操作以及输入操作已经完成,即已完成初始化操作,也就是说在ngOnInit函数中我们已经能够操作组件/指令中传入的数据了;我们在ngOnInit中最常见的操作就是做一些初始化操作。

// hello-world.ts
import { Component, Input, OnInit } from '@angular/core';

@Component({
    selector: 'hello-world',
    template: `<p>Hello {{name}}!</p>`
})
class HelloWorld implements OnInit {
    @Input()
    name: string;

    constructor() {
        // constructor中还不能获取到组件/指令中被传入的数据
        console.log(this.name);     // undefined
    }

    ngOnInit() {
        // ngOnInit中已经能够获取到组件/指令中被传入的数据
        console.log(this.name);     // 传入的数据
    }
}

总结

constructor()中只进行依赖注入

ngOnInit()里面进行真正的业务操作

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值