如何将异步数据从组件传递到组件?

时间:2018-08-06 15:07:16

标签: angularjs

我有一个父级组件

angular.module('app')
  .component('parentComponent', {
    template: `
          <child-component data="myData"></child-component>
    `,

我通过异步调用获得myData

myMethod(params).then(data => {
    $ctrl.data = data;
});

然后将其传递给我的子组件,在其中我希望对其进行修改并将其显示在模板中

angular.module('app')
.component('childComponent', {
    restrict: 'E',
    replace: true,
    templateUrl: '',
    bindings: {
        data: '='
    },

    controller: function () {
    const $ctrl = this;

    $ctrl.$onInit = function () {
        console.log($ctrl.data);
    }
});

问题是数据在接收之前就已经传递进来,因此在子组件中未定义。

我不确定在传递数据之前如何等待数据。

1 个答案:

答案 0 :(得分:2)

使用$onChanges Life-Cycle Hook

app.component('childComponent', {
    templateUrl: '',
    bindings: {
        data: '<'
    },    
    controller: function () {
        const $ctrl = this;        
        $ctrl.$onChanges = function (changes) {
            changes.data && console.log(changes.data.currentValue);
        };
    }
});

从文档中:

  

生命周期挂钩

     

指令控制器可以提供以下指令,这些指令由AngularJS在指令生命周期的各个点调用:

     
      
  • $onChanges(changesObj)-每当单向(<)或插值(@)绑定更新时调用。 changesObj是一个哈希,其键是已更改的绑定属性的名称,值是{ currentValue, previousValue, isFirstChange() }形式的对象。使用此挂钩可触发组件内的更新,例如克隆绑定值以防止外部值的意外突变。请注意,初始化绑定时也会调用此方法。
  •   
     

— AngularJS Comprehensive API Reference - Life-Cycle Hooks