angularjs - 何时使用 AngularJS `$onInit` 生命周期 Hook

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

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

Due to 38f8c9, directive bindings are no longer available in the constructor.

To migrate your code:

  • If you specified $compileProvider.preAssignBindingsEnabled(true) you need to first migrate your code so that the flag can be flipped to false. The instructions on how to do that are available in the "Migrating from 1.5 to 1.6" guide. Afterwards, remove the $compileProvider.preAssignBindingsEnabled(true) statement.

AngularJS Developer Guide - Migrating to V1.7 - Compile



Due to bcd0d4, pre-assigning bindings on controller instances is disabled by default. We strongly recommend migrating your applications to not rely on it as soon as possible.

Initialization logic that relies on bindings being present should be put in the controller's $onInit() method, which is guaranteed to always be called after the bindings have been assigned.

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


必须将代码移至 $onInit Life-Cycle Hook 时的用例是什么? ?我们什么时候可以将代码留在 Controller 构造函数中?

最佳答案

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

例子:
你有一个这样的状态定义:

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

可以绑定(bind)myResolve的结果像这样到您的组件:
export const CategoryComponent = {
  bindings: {
    myResolve: "<"
  },
  controller: Category
};

如果您现在退出 this.myResolveconstructor$onInit你会看到这样的东西:
constructor() {
  console.log(this.myResolve); // <-- undefined
}

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

因此,您的构造函数应该只包含如下构造代码:
constructor() {
  this.myArray = [];
  this.myString = "";
}

每个 Angular 特定的初始化和绑定(bind)或依赖使用都应该在 $onInit 中。

关于angularjs - 何时使用 AngularJS `$onInit` 生命周期 Hook ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51273521/

相关文章:

javascript - Node、express 和 Angular 的重定向问题

javascript - 从 Controller 中删除可变逻辑,将其转移到服务中

angularjs - $rootScope.$broadcast 不起作用

angularjs - 测试指令中正文点击的最有 Angular 的方法是什么?

javascript - 同时添加两个元素

javascript - 如何在 Angularjs 中将值从服务传递到 Controller

AngularJS - 如何强制更新范围(数组项的 promise )

angularjs - Angular 组件绑定(bind)对象未初始化

angularjs - AngularJS 1.5 中同一组件中有多个模板

javascript - 在 Angular 中更新 View 后如何避免旧值闪烁?