【问题标题】:Using $onChanges vs $onInit in angular component在角度组件中使用 $onChanges 与 $onInit
【发布时间】:2017-05-24 20:23:59
【问题描述】:

使用Controller1Controller2 有区别吗?

angular.module('app', [])
.component('foo', {
    templateUrl: 'foo.html',
    bindings: {
        user: '<',
    },
    controller: Controller1, //Or Controller2
});

function Controller1(){
    this.$onInit = function(){
      this.user = angular.copy(this.user);
    };

    this.$onChanges = function(changes){
      if(changes.user && !changes.user.isFirstChange()){
        this.user = angular.copy(changes.user.currentValue);
      }
    };
}


function Controller2(){
    this.$onChanges = function(changes){
      if(changes.user){
        this.user = angular.copy(changes.user.currentValue);
      }
    };
}

既然我可以在 $onChanges 中做同样的事情并保存一些行,我为什么还要打扰 $onInit

这种类型的初始化在$onChanges$onInit 中是否更适合其他类型的初始化?

【问题讨论】:

    标签: javascript angularjs angular-components


    【解决方案1】:

    $onInit

    在元素上的所有控制器都已构建并初始化其绑定之后(以及在此元素上的指令的前后链接函数之前)在每个控制器上调用。这是放置控制器初始化代码的好地方。

    $onChanges

    $onChanges 生命周期钩子被调用有几个原因。第一个是组件初始化,它在运行时传递初始更改对象,因此我们可以立即获取数据。它被调用的第二个原因是仅当从父组件绑定到的“$onChanges 被调用,您将获得一个特殊的更改对象,您可以将其挂钩,我们将在接下来的部分中进行探讨。

    主要的实际区别是$onInit 将仅在指令初始化时调用,但$onChanges 将在初始化期间以及&lt;@ 变量更改时调用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-22
      • 1970-01-01
      • 1970-01-01
      • 2020-08-23
      • 2021-09-27
      • 2019-10-18
      • 2020-12-09
      • 2018-09-13
      相关资源
      最近更新 更多