Angular 构造函数和ngOnInit之间的区别

Angular 构造函数和ngOnInit之间的区别,angular,typescript,ngoninit,Angular,Typescript,Ngoninit,Angular默认情况下提供生命周期挂钩ngOnInit 如果我们已经有了构造函数,为什么要使用ngOnInit?构造函数是类的默认方法,在实例化类时执行,并确保类及其子类中字段的正确初始化。Angular或更好的依赖注入程序(DI)分析构造函数参数,当它通过调用new MyClass()创建新实例时,它会尝试查找与构造函数参数类型匹配的提供程序,解析它们并将它们传递给构造函数 new MyClass(someArg); ngOnInit是Angular调用的生命周期挂钩,用于指示Angula

Angular默认情况下提供生命周期挂钩
ngOnInit


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

构造函数是类的默认方法,在实例化类时执行,并确保类及其子类中字段的正确初始化。Angular或更好的依赖注入程序(DI)分析构造函数参数,当它通过调用
new MyClass()
创建新实例时,它会尝试查找与构造函数参数类型匹配的提供程序,解析它们并将它们传递给构造函数

new MyClass(someArg);
ngOnInit
是Angular调用的生命周期挂钩,用于指示Angular已完成组件的创建

import {Component} from '@angular/core';
@Component({})
class NGONINITTEST implements onInit{
   constructor(){}
   //ngOnInit calls by Angular
   ngOnInit(){
     console.log("Testing ngOnInit");
   }
}
为了使用它,我们必须像这样导入
OnInit
(实际上实施
OnInit
不是强制性的,但被认为是良好的实践):

然后要使用方法
OnInit
,我们必须实现如下类:

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

  ngOnInit() {
     // Called after the constructor and called  after the first ngOnChanges() 
  }
}
   constructor(private http: Http, private customService: CustomService) {}
实现此接口以在指令的数据绑定属性初始化后执行自定义初始化逻辑。 在第一次检查指令的数据绑定属性之后立即调用ngOnInit, 在检查它的孩子之前。 当指令被实例化时,它只被调用一次

大多数情况下,我们使用
ngOnInit
进行所有初始化/声明,避免在构造函数中工作。构造函数应该只用于初始化类成员,而不应该执行实际的“工作”

因此,您应该使用
constructor()
来设置依赖项注入,而不是其他。ngOnInit()是一个更好的“起点”——它是解决组件绑定的位置/时间

有关更多信息,请参阅此处:


构造函数是类的默认方法,在实例化类时执行,确保类及其子类中字段的正确初始化。Angular或更好的依赖注入程序(DI)分析构造函数参数,当它通过调用
new MyClass()
创建新实例时,它会尝试查找与构造函数参数类型匹配的提供程序,解析它们并将它们传递给构造函数

new MyClass(someArg);
ngOnInit
是Angular调用的生命周期挂钩,用于指示Angular已完成组件的创建

import {Component} from '@angular/core';
@Component({})
class NGONINITTEST implements onInit{
   constructor(){}
   //ngOnInit calls by Angular
   ngOnInit(){
     console.log("Testing ngOnInit");
   }
}
为了使用它,我们必须像这样导入
OnInit
(实际上实施
OnInit
不是强制性的,但被认为是良好的实践):

然后要使用方法
OnInit
,我们必须实现如下类:

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

  ngOnInit() {
     // Called after the constructor and called  after the first ngOnChanges() 
  }
}
   constructor(private http: Http, private customService: CustomService) {}
实现此接口以在指令的数据绑定属性初始化后执行自定义初始化逻辑。 在第一次检查指令的数据绑定属性之后立即调用ngOnInit, 在检查它的孩子之前。 当指令被实例化时,它只被调用一次

大多数情况下,我们使用
ngOnInit
进行所有初始化/声明,避免在构造函数中工作。构造函数应该只用于初始化类成员,而不应该执行实际的“工作”

因此,您应该使用
constructor()
来设置依赖项注入,而不是其他。ngOnInit()是一个更好的“起点”——它是解决组件绑定的位置/时间

有关更多信息,请参阅此处:

    • 简短而简单的答案是

      构造函数
      构造函数
      是一个
      默认方法
      在构造组件时运行(默认)。当您创建类的
      实例时,也会调用
      构造函数(默认方法)
      。因此,换句话说,当组件被构造或/或创建实例时,调用构造函数(默认方法)
      ,并在其中写入相关代码。基本上,通常在
      Angular2
      中,当构建组件以供进一步使用时,它用于注入类似
      服务的内容

      OnInit
      :ngOnInit是组件的生命周期挂钩,当组件初始化时,它首先在
      构造函数(默认方法)
      之后运行

      因此,将首先调用构造函数,然后在构造函数方法之后调用Oninit

      let instance = new NGONINITTEST();
      
      boot.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() {
          }
      }
      
      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;
        }
      
      }
      
      资源:

      您可以检查这个,它显示了这两个方面的实现。

      简短而简单的答案是

      构造函数
      构造函数
      是一个
      默认方法
      在构造组件时运行(默认)。当您创建类的
      实例时,也会调用
      构造函数(默认方法)
      。因此,换句话说,当组件被构造或/或创建实例时,调用构造函数(默认方法)
      ,并在其中写入相关代码。基本上,通常在
      Angular2
      中,当构建组件以供进一步使用时,它用于注入类似
      服务的内容

      OnInit
      :ngOnInit是组件的生命周期挂钩,当组件初始化时,它首先在
      构造函数(默认方法)
      之后运行

      因此,将首先调用构造函数,然后在构造函数方法之后调用Oninit

      let instance = new NGONINITTEST();
      
      boot.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() {
          }
      }
      
      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;
        }
      
      }
      
      资源:


      您可以检查这个,它显示了这两个方面的实现。

      我认为最好的例子是使用服务。L
      let instance = new NGONINITTEST();
      
      instance.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!');
        }
      }
      
      <my-app>
         <child-comp [i]='prop'>
      
      MyAppView
        - MyApp component instance
        - my-app host element data
             ChildCompnentView
               - ChildComponent component instance
               - child-comp host element data  
      
      class Some {
        constructor() {
          this.init();
        }
      
        init() {...}
      }
      
      constructor(
        public foo: Foo,
        /* verbose list of dependencies */
      ) {
        // time-sensitive initialization code
        this.bar = foo.getBar();
      }
      
      ngOnInit() {
        // rest of initialization code
      }
      
      constructor(
        public foo: Foo,
        public errorHandler: ErrorHandler
      ) {}
      
      async ngOnInit() {
        try {
          await this.foo.getBar();
          await this.foo.getBazThatDependsOnBar();
        } catch (err) {
          this.errorHandler.handleError(err);
        }
      }
      
      ngOnInit() {
        this.someMethod();
        super.ngOnInit();
      }
      
       constructor(translate: TranslateService, private oauthService: OAuthService) {
          translate.setDefaultLang('En');
              translate.use('En');}
      
      ngOnInit() {
          this.items = [
            { label: 'A', icon: 'fa fa-home', routerLink: ['/'] },
            { label: 'B', icon: 'fa fa-home', routerLink: ['/'] }]
      }
      
      constructor(private 
          service1: Service1,
          service2: Service2
      ){};
      
      ngOnInit(){
          service1.someWork();
      };
      
      @Input itemFromParent: string;
      @ViewChild('childView') childView;
      
      constructor(){
          console.log(itemFromParent); // KO
          // childView is undefined here
      };
      
      ngOnInit(){
          console.log(itemFromParent); // OK
          // childView is undefined here, you can manipulate here
      };