When to use the AngularJS `$onInit` Life-Cycle Hook

后端 未结 1 455
心在旅途
心在旅途 2020-11-29 10:23

With the release of AngularJS V1.7, the option to pre-assign bindings to has deprecated and removed:

Due to 38f8c9, directive bindings are no lon

相关标签:
1条回答
  • 2020-11-29 11:15

    Code has to be moved in the $onInit function, when it depends on bindings, because these bindings are not available within this in the constructor. They get assigned AFTER instantiation of the component class.

    Example: You have a state definition like this:

    $stateProvider.state("app", {
      url: "/",
      views: {
        "indexView": {
          component: "category"
        }
      },
      resolve: {
        myResolve: (someService) => {
          return someService.getData();
        }
      }
    });
    

    You can bind the result of myResolve to your component like this:

    export const CategoryComponent = {
      bindings: {
        myResolve: "<"
      },
      controller: Category
    };
    

    If you now log out this.myResolve in the constructor and in $onInit you will see something like this:

    constructor() {
      console.log(this.myResolve); // <-- undefined
    }
    
    $onInit() {
      console.log(this.myResolve); // <-- result of your resolve
    }
    

    So, your constructor should only contain constructing code like:

    constructor() {
      this.myArray = [];
      this.myString = "";
    }
    

    Every angular specific initialisation and binding or dependency usage should be in $onInit

    0 讨论(0)
提交回复
热议问题