【问题标题】:Angular 1.5: How to pass async data to child componentAngular 1.5:如何将异步数据传递给子组件
【发布时间】:2017-07-14 23:19:10
【问题描述】:

我正在尝试将异步数据传递给子 d3 组件以绘制图表。

parentComponent.controller = function(){
  this.data = null;
  this.$postLink = function () {
    console.log('postlink')
    async(url).then(function(data){
        this.data = data;
    }.bind(this))
  }
}

childComponent({
  bindings: {
    data: '<'
  },
  controller: function(){
    this.$onInit = function () {
        console.log('init')
        console.log(this.data)
    }

    this.$onChanges = function () {
        console.log('onchange')
        console.log(this.data)
    }

    this.$doCheck = function () {
        console.log('docheck')
        console.log(this.data)
    }
  }
})

日志如下所示:

onchange null
init null
docheck null
postlink

但如果我同步更改父数据,它会起作用。

this.$postLink = function () {
    console.log('postlink')
    this.data = 'new data';
}

// logs
.
.
.
postlink
docheck 'new data'
onchange 'new data'

谁能告诉我为什么这不起作用以及如何制作 d3 角度组件?

【问题讨论】:

  • 什么是异步()?如果您“在其背后”修改模型,即不使用 $timeout、$interval 或 $http 之类的服务之一,Angular 不会知道模型已更改。在这种情况下,您需要调用 $scope.$apply()。
  • 您的 html 结构如何将数据传递给子组件?请也粘贴那个

标签: angularjs asynchronous d3.js


【解决方案1】:

使用$q.when 方法将可疑承诺转换为$q 服务承诺。

parentComponent.controller = function($q){
  this.data = null;
  this.$postLink = function () {
    console.log('postlink')
    //USE $q.when
    $q.when(async(url)).then(function(data){
        this.data = data;
    }.bind(this))
  }
}

$q 服务承诺 .then 方法与 AngularJS 摘要循环集成,因此对模型的更改将自动更新控制器和 DOM。

什么时候

将可能是值或(第 3 方)then-able 承诺的对象包装到 $q 承诺中。当您处理的对象可能是也可能不是 Promise 时,或者当 Promise 来自不可信的来源时,这很有用。

-- AngularJS $q Service API Reference - when

【讨论】:

  • 感谢您的回答。看起来 $q 或 $http 或 $parentScope.digest() 都可以让它工作!
  • 使用$q.when 更安全。手动调用$digest 风险Error: $rootScope:inprog。如果特定范围内的观察者在摘要范围之外修改模型,也会产生难以调试的错误。小心接受任何建议使用 $digest 的建议。
猜你喜欢
  • 1970-01-01
  • 2019-01-13
  • 2017-12-17
  • 2016-08-31
  • 2021-01-23
  • 2018-11-30
  • 1970-01-01
  • 2017-02-28
  • 1970-01-01
相关资源
最近更新 更多