【问题标题】:When to use the AngularJS `$onInit` Life-Cycle Hook何时使用 AngularJS `$onInit` Life-Cycle Hook
【发布时间】:2018-12-18 18:56:05
【问题描述】:

随着 AngularJS V1.7 的发布,预先分配绑定到的选项已被弃用并删除:

由于38f8c9构造函数中不再提供指令绑定

要迁移您的代码:

  • 如果您指定了$compileProvider.preAssignBindingsEnabled(true),您需要首先迁移您的代码,以便可以将标志翻转为false"Migrating from 1.5 to 1.6" guide 中提供了有关如何执行此操作的说明。然后,删除 $compileProvider.preAssignBindingsEnabled(true) 语句。

——AngularJS Developer Guide - Migrating to V1.7 - Compile

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

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

——AngularJS Developer Guide - Migrating from v1.5 to v1.6 - $compile

当代码必须移动到$onInit Life-Cycle Hook 时,有哪些用例?我们什么时候可以把代码留在控制器构造函数中?

【问题讨论】:

  • 如果代码不使用任何绑定,你可以留下它——或者你认为这里有更深层次的东西?

标签: angularjs angularjs-directive angularjs-components angularjs-1.7


【解决方案1】:

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

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

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

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

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

如果您现在在constructor$onInit 中注销this.myResolve,您将看到如下内容:

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

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

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

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

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

【讨论】:

  • 试着想想为什么我会在构造函数中留下一些东西,而不是直接把所有东西都放在$onInit()中。我理解您可以争辩说,这不如在构造函数中对非绑定相关代码进行分组那样富有表现力,但这是迄今为止我所获得的最佳范围。
  • 从 AngularJs 的角度来看,你是完全正确的。 $onInit 基本上就足够了。但请记住,$onChanges 在 $onInit 之前运行(在 AngularJs 1.5.5 及更高版本中),您可能会使用未初始化的属性。从 OOP 的角度来看,在构造函数中初始化是首选。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-30
  • 1970-01-01
  • 1970-01-01
  • 2018-08-15
  • 2016-06-07
  • 1970-01-01
相关资源
最近更新 更多