Difference between Constructor and ngOnInit

2018-12-31 04:07发布

Angular provides life cycle hook ngOnInit by default.

Why should ngOnInit be used, if we already have a constructor?

20条回答
余生无你
2楼-- · 2018-12-31 04:13

To test this, I wrote this code, borrowing from the NativeScript Tutorial:

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;
  }

}

Console output

JS: *** User class constructor property ***  
JS: *** User class constructor constructor ***  
JS: *** Login Component Constructor ***  
JS: *** User class constructor ngOnInit ***  
JS: *** Login Component ngOnInit ***  
查看更多
明月照影归
3楼-- · 2018-12-31 04:14

I will just add one important thing that was skipped in the explanations above and explains when you MUST use ngOnInit.

If you are doing any manipulation of the component's DOM via e.g. ViewChildren, ContentChildren or ElementRef, your native elements will not be available during the constructor phase.

However, since ngOnInit happens once the component has been created and the checks (ngOnChanges) have been called you can access the DOM at this point.

export class App implements OnInit {
  @ViewChild('myTemplate') myTemplate: TemplateRef<any>;

  constructor(private elementRef: ElementRef) {
     // this.elementRef.nativeElement is undefined here
     // this.myTemplate is undefined here
  }

  ngOnInit() {
     // this.elementRef.nativeElement can be used from here on
     // this.myTemplate can be used from here on
  }
}
查看更多
回忆,回不去的记忆
4楼-- · 2018-12-31 04:15

Constructor is the first, and it happens sometimes when @input data is null! so we use Constructor for declare services and ngOnInit happens after. Exsample for contrutor:

 constructor(translate: TranslateService, private oauthService: OAuthService) {
    translate.setDefaultLang('En');
        translate.use('En');}

Exsample for onInit:

ngOnInit() {
    this.items = [
      { label: 'A', icon: 'fa fa-home', routerLink: ['/'] },
      { label: 'B', icon: 'fa fa-home', routerLink: ['/'] }]
}

I think that onInit is like InitialComponents() in winForm .

查看更多
其实,你不懂
5楼-- · 2018-12-31 04:16

constructor() is used to do dependency injection.

ngOnInit(), ngOnChanges() and ngOnDestroy() etc. are lifecycle methods. ngOnChanges() will be the first to be called, before ngOnInit(), when the value of a bound property changes, it will NOT be called if there is no change. ngOnDestroy() is called when the component is removed. To use it, OnDestroy needs to be implemented by the class.

查看更多
十年一品温如言
6楼-- · 2018-12-31 04:17

Both methods have different goals/responsibilities. The task of the constructor (which is a language supported feature) is to make sure that the representation invariant holds. Otherwise stated to make sure that the instance is valid by giving correct values to the members. It is up to the developer to decide what 'correct' means.

The task of the onInit() method (which is an angular concept) is to allow method invocations on a correct object (representation invariant). Each method should in turn make sure that the representation invariant holds when the method terminates.

The constructor should be used to create 'correct' objects, the onInit method gives you the opportunity to invoke method calls at a well defined instance.

查看更多
几人难应
7楼-- · 2018-12-31 04:17

constructor() is the default method in the Component life cycle and is used for dependency injection. Constructor is a Typescript Feature.

ngOnInit() is called after the constructor and ngOnInit is called after the first ngOnChanges.

i.e. Constructor()->ngOnChanges()->ngOnInit()

as mentioned above ngOnChanges() is called when an input or output binding value changes.

查看更多
登录 后发表回答