何时使用AngularJS`$ onInit`生命周期挂钩

geo*_*awg 5 angularjs angularjs-directive angularjs-components angularjs-1.7

随着AngularJS V1.7的发布,已经不建议使用和删除将绑定预先分配给的选项:

由于38f8c9指令绑定在构造函数中不再可用

迁移代码:

  • 如果指定$compileProvider.preAssignBindingsEnabled(true),则需要首先迁移代码,以便将标志翻转到false。有关如何执行此操作的说明,请参见 “从1.5迁移到1.6”指南。之后,删除该$compileProvider.preAssignBindingsEnabled(true)语句。

AngularJS开发人员指南-迁移至V1.7-编译

由于bcd0d4的缘故,默认情况下在控制器实例上禁用了预分配绑定。 强烈建议迁移您的应用程序,使其不尽快依赖它。

依赖于存在的绑定的初始化逻辑应该放在控制器的$onInit()方法中,保证在分配了绑定之后总是调用该方法。

AngularJS开发人员指南-从v1.5迁移到v1.6-$ compile

将代码移至$onInit生命周期挂钩的用例是什么?什么时候才能将代码保留在控制器构造函数中?

sci*_*per 9

当代码$onInit依赖于绑定时,必须在函数中移动代码,因为这些绑定this在构造函数中不可用。它们在组件类实例化后被分配。

示例:您有这样的状态定义:

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

您可以myResolve像这样将 的结果绑定到您的组件:

export const CategoryComponent = {
  bindings: {
    myResolve: "<"
  },
  controller: Category
};
Run Code Online (Sandbox Code Playgroud)

如果你现在退出this.myResolve constructor $onInit你会看到这样的事情:

constructor() {
  console.log(this.myResolve); // <-- undefined
}

$onInit() {
  console.log(this.myResolve); // <-- result of your resolve
}
Run Code Online (Sandbox Code Playgroud)

因此,您的构造函数应该只包含如下构造代码:

constructor() {
  this.myArray = [];
  this.myString = "";
}
Run Code Online (Sandbox Code Playgroud)

每个角度特定的初始化和绑定或依赖项使用都应该在 $onInit