Angular默认提供了生命周期钩子ngOnInit。

为什么要使用ngOnInit,如果我们已经有一个构造函数?


当前回答

为了测试这一点,我从NativeScript教程中借鉴编写了以下代码:

user.ts

export class User {
    email: string;
    password: string;
    lastLogin: Date;

    constructor(msg:string) {        
        this.email = "";
        this.password = "";
        this.lastLogin = new Date();
        console.log("*** User class constructor " + msg + " ***");
    }

    Login() {
    }
}

login.component.ts

import {Component} from "@angular/core";
import {User} from "./../../shared/user/user"

@Component({
  selector: "login-component",
  templateUrl: "pages/login/login.html",
  styleUrls: ["pages/login/login-common.css", "pages/login/login.css"]
})
export class LoginComponent {

  user: User = new User("property");  // ONE
  isLoggingIn:boolean;

  constructor() {    
    this.user = new User("constructor");   // TWO
    console.log("*** Login Component Constructor ***");
  }

  ngOnInit() {
    this.user = new User("ngOnInit");   // THREE
    this.user.Login();
    this.isLoggingIn = true;
    console.log("*** Login Component ngOnInit ***");
  }

  submit() {
    alert("You’re using: " + this.user.email + " " + this.user.lastLogin);
  }

  toggleDisplay() {
    this.isLoggingIn = !this.isLoggingIn;
  }

}

控制台输出

JS: *** User class constructor property ***  
JS: *** User class constructor constructor ***  
JS: *** Login Component Constructor ***  
JS: *** User class constructor ngOnInit ***  
JS: *** Login Component ngOnInit ***  

其他回答

在Angular生命周期中

1) Angular注入器检测构造函数参数和实例化类。

2)下一个角调用生命周期

Angular生命周期钩子

调用指令参数绑定。

开始角渲染…

调用具有角生命周期状态的其他方法。

构造函数()可以接受参数并用于依赖注入,构造函数()用于添加服务对象。

构造函数在ngOnint()之前调用;

ngOnInit()用于用必要的服务函数调用操作组件,通常,ngOnInit()中调用服务,而不是在构造函数中调用服务

这里需要注意两点:

每当该类创建对象时,都会调用构造函数。 一旦组件创建,就调用ngOnInit。

两者都有不同的可用性。

首先,ngOnInit是Angular生命周期的一部分,而constructor是ES6 JavaScript类的一部分,所以主要的区别就是从这里开始的!

请看下面我创建的图表,它展示了Angular的生命周期。

在Angular2+中,我们使用构造函数为我们做DI(依赖注入),而在Angular 1中,它是通过调用String方法并检查注入了哪个依赖。

正如你在上面的图表中看到的,ngOnInit是在构造函数准备好之后发生的,ngOnChnages和在组件为我们准备好之后被触发。所有的初始化都可以在这个阶段进行,一个简单的示例是注入一个服务并在init上初始化它。

好的,我还分享了一个示例代码给你看,看看我们如何在下面的代码中使用ngOnInit和构造函数:

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


@Component({
 selector: 'my-app',
 template: `<h1>App is running!</h1>
  <my-app-main [data]=data></<my-app-main>`,
  styles: ['h1 { font-weight: normal; }']
})
class ExampleComponent implements OnInit {
  constructor(private router: Router) {} //Dependency injection in the constructor
  
  // ngOnInit, get called after Component initialised! 
  ngOnInit() {
    console.log('Component initialised!');
  }
}

两种方法都有不同的目标/职责。构造函数(这是语言支持的特性)的任务是确保表示不变量成立。否则,通过给成员正确的值来确保实例是有效的。“正确”的含义由开发者决定。

onInit()方法(这是一个angular概念)的任务是允许在正确的对象上调用方法(表示不变)。每个方法都应该依次确保在方法终止时表示不变量保持不变。

构造函数应该用来创建“正确的”对象,onInit方法让你有机会在一个定义良好的实例中调用方法调用。