[英]How to pass async data to child component from parent component?
I have a parent component 我有一个父组件
angular.module('app')
.component('parentComponent', {
template: `
<child-component data="myData"></child-component>
`,
I'm getting myData
by asynchronous call 我通过异步调用获取
myData
myMethod(params).then(data => {
$ctrl.data = data;
});
and then I pass it down to my child component where I want modify it and display it in the template 然后将其传递给我的子组件,在该子组件中进行修改并将其显示在模板中
angular.module('app')
.component('childComponent', {
restrict: 'E',
replace: true,
templateUrl: '',
bindings: {
data: '='
},
controller: function () {
const $ctrl = this;
$ctrl.$onInit = function () {
console.log($ctrl.data);
}
});
Problem is that data gets passed in before it is received and because of it it is undefined in the child component. 问题在于数据在被接收之前就已经传递进来,并且由于它在子组件中未定义。
I'm not sure how do I wait for the data before passing it down. 我不确定在传递数据之前如何等待数据。
Use the $onChanges
Life-Cycle Hook 使用
$onChanges
生命周期挂钩
app.component('childComponent', {
templateUrl: '',
bindings: {
data: '<'
},
controller: function () {
const $ctrl = this;
$ctrl.$onChanges = function (changes) {
changes.data && console.log(changes.data.currentValue);
};
}
});
From the Docs: 从文档中:
Life-cycle hooks
生命周期挂钩
Directive controllers can provide the following methods that are called by AngularJS at points in the life-cycle of the directive:
指令控制器可以提供以下指令,这些指令在指令的生命周期内由AngularJS调用:
$onChanges(changesObj)
- Called whenever one-way (<
) or interpolation (@
) bindings are updated.$onChanges(changesObj)
-每当单向(<
)或插值(@
)绑定更新时调用。 ThechangesObj
is a hash whose keys are the names of the bound properties that have changed, and the values are an object of the form{ currentValue, previousValue, isFirstChange() }
.changesObj
是一个哈希,其键是已更改的绑定属性的名称,并且值是{ currentValue, previousValue, isFirstChange() }
形式的对象。 Use this hook to trigger updates within a component such as cloning the bound value to prevent accidental mutation of the outer value.使用此挂钩可触发组件内的更新,例如克隆绑定值以防止外部值的意外突变。 Note that this will also be called when your bindings are initialized.
请注意,初始化绑定时也会调用此方法。
— AngularJS Comprehensive API Reference - Life-Cycle Hooks
— AngularJS综合API参考-生命周期挂钩
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.