为什么要在AngularJS中使用$ onInit? [英] Why to use $onInit in AngularJS?

查看:262
本文介绍了为什么要在AngularJS中使用$ onInit?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在AngularJS中,如果没有该功能就可以执行相同的初始化,那么$onInit函数的目的是什么?

In AngularJS, what is the purpose of the $onInit function if I can do the same initialization without that function?

例如:

module.component("myComponent", {
        ...
        controller: function() {
            const $ctrl = this;

            $ctrl.$onInit = () => {
                $ctrl.var1 = "hello";
                $ctrl.var2 = { test: 3 };
            }
        }
    });

也可以这样:

module.component("myComponent", {
        ...
        controller: function() {
            const $ctrl = this;

            $ctrl.var1 = "hello";
            $ctrl.var2 = { test: 3 };
        }
    });

在某些情况下需要$onInit吗?

推荐答案

每个 AngularJS文档

在元素上的所有控制器均已构建并初始化其绑定之后(且在该元素上的指令的pre& post链接功能之前),在每个控制器上调用.

Called on each controller after all the controllers on an element have been constructed and had their bindings initialized (and before the pre & post linking functions for the directives on this element).

这给您两个保证:

  1. 此元素上的所有控制器均已构建
  2. 前置&此元素的发布链接功能尚未执行

与您的第一种方法相反,后者无法保证所有这些事实(尽管第二种方法很可能是 ).

In contrast to your first method, where neither of these facts are guaranteed (though the second one is highly probable).

此外,就样式和可读性而言,它使潜在的阅读者/审阅者非常清楚这是您作为开发人员打算在初始化此控制器时运行的代码.

In addition, as a matter of style and readability, it makes it very clear to a potential reader/reviewer that this is code that you as the developer intended to run upon initialization of this controller.

这篇关于为什么要在AngularJS中使用$ onInit?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆