【问题标题】:How to pass async data to child component from parent component?如何将异步数据从父组件传递给子组件?
【发布时间】:2019-01-13 14:14:26
【问题描述】:

我有一个父组件

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);
    }
});

问题是数据在接收之前就被传入了,因此它在子组件中是未定义的。

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

【问题讨论】:

  • &lt;child-component ng-if="data" ...&gt;

标签: angularjs


【解决方案1】:

使用$onChangesLife-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) - 每当单向 (&lt;) 或插值 (@) 绑定更新时调用。 changesObj 是一个散列,其键是已更改的绑定属性的名称,值是{ currentValue, previousValue, isFirstChange() } 形式的对象。使用此钩子触发组件内的更新,例如克隆绑定值以防止外部值的意外突变。请注意,这也会在您的绑定初始化时调用。

— AngularJS Comprehensive API Reference - Life-Cycle Hooks

【讨论】:

    猜你喜欢
    • 2021-09-12
    • 2019-10-05
    • 2020-11-01
    • 2021-11-06
    • 2020-05-27
    • 2017-07-14
    • 2020-08-06
    • 2021-07-12
    • 1970-01-01
    相关资源
    最近更新 更多