何时使用AngularJS`$ onInit`生命周期挂钩 [英] When to use the AngularJS `$onInit` Life-Cycle Hook
问题描述
随着AngularJS V1.7的发布,已经不建议使用和取消预定义绑定的选项:
With the release of AngularJS V1.7, the option to pre-assign bindings to has deprecated and removed:
由于 38f8c9 ,方向绑定不再可用构造函数.
要迁移代码,请执行以下操作:
To migrate your code:
- 如果指定了
$compileProvider.preAssignBindingsEnabled(true)
,则需要首先迁移代码,以便将标志翻转到false
. "中提供了有关操作方法的说明. ;从1.5迁移到1.6";指南.然后,删除$compileProvider.preAssignBindingsEnabled(true)
语句.
- If you specified
$compileProvider.preAssignBindingsEnabled(true)
you need to first migrate your code so that the flag can be flipped tofalse
. 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开发人员指南-迁移至V1.7-编译 >
由于 bcd0d4 ,控制器实例上的预分配绑定已被禁用默认. 我们强烈建议迁移您的应用程序,使其不要尽快依赖它.
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.
依赖于存在的绑定的初始化逻辑应放在控制器的$onInit()
方法中,该方法确保在分配了绑定后总是被称为.
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开发人员指南-从v1迁移. 5至v1.6-$ compile
What are the use cases when code has to be moved to the $onInit
Life-Cycle Hook? When can we just leave the code in the controller construction function?
推荐答案
当代码依赖于绑定时,必须在$onInit
函数中移动代码,因为这些绑定在构造函数的this
中不可用.它们在组件类的实例化之后被分配.
Code has to be moved in the $onInit
function, when it depends on bindings, because these bindings are not available within this
in the constructor. They get assigned AFTER instantiation of the component class.
示例: 您具有如下状态定义:
Example: You have a state definition like this:
$stateProvider.state("app", {
url: "/",
views: {
"indexView": {
component: "category"
}
},
resolve: {
myResolve: (someService) => {
return someService.getData();
}
}
});
您可以将myResolve
的结果绑定到组件,如下所示:
You can bind the result of myResolve
to your component like this:
export const CategoryComponent = {
bindings: {
myResolve: "<"
},
controller: Category
};
如果现在在constructor
和$onInit
中登出this.myResolve
,您将看到类似以下内容:
If you now log out this.myResolve
in the constructor
and in $onInit
you will see something like this:
constructor() {
console.log(this.myResolve); // <-- undefined
}
$onInit() {
console.log(this.myResolve); // <-- result of your resolve
}
因此,您的构造函数应仅包含类似以下的构造代码:
So, your constructor should only contain constructing code like:
constructor() {
this.myArray = [];
this.myString = "";
}
每个特定于角度的初始化和绑定或依赖项的使用都应在$onInit
Every angular specific initialisation and binding or dependency usage should be in $onInit
这篇关于何时使用AngularJS`$ onInit`生命周期挂钩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!