【问题标题】:Passing array of interfaces between components angular 2在组件角度2之间传递接口数组
【发布时间】:2018-03-13 12:14:30
【问题描述】:

我在通过@Input 在组件之间传递数据(数组)时遇到了一些麻烦,有一些代码。 parent.component.ts:

public ngOnInit() {
    this.applications = new Array<ApplicationEntryInterface>();
(...)
let shortTermData = new ShortTermApplicationAdapter(application);
this.applications.push(shortTermData);
console.log(this.applications);
}

这个 console.log 显示了正常的数组 父组件.html

<student-application-overview [applicationsEntry]="applications"></student-application-overview>

子组件:

@Input('applicationsEntry') public applicationsEntry: Array<ApplicationEntryInterface>;
 ngOnChanges() {
console.log(this.applicationsEntry);
console.log(this.applicationsEntry.length); <--- shows 0
}

这表明 不可能在for、foreach等中迭代它,只有*ngFor有效,this.applicationsEntry.length等于0,我该如何处理? 我也使用了@Input (..) set (..) { (..) },它给出了相同的结果

【问题讨论】:

  • 将数组传递给子组件的方式看起来是正确的,如果第二个屏幕抓取是来自您孩子的日志,那么它在那里看起来也是正确的。我们能否看到您在组件代码中调用forEachlength 的位置?我最好的猜测是,您传入的数组不会立即在您的子组件中可用,特别是如果您的模板 HTML 中的 *ngFor 工作
  • 刚刚编辑,同样的 forEach 将这个数组视为 0 长度。
  • 好吧,我刚刚意识到,我在父组件中使用了异步函数(与rest api通信),无论如何,最新的数组没有设置在更改上(只有正文)。
  • 嗯,明白了。看起来异步未触发更改检测可能this question 有关,它没有令人满意的解决方案。一种选择(如果更改检测确实是问题)是传入第二个输入(例如changeTrigger),不绑定到异步调用,当您返回异步调用的结果时更新。当您在父级中调用changeTrigger++ 时,它会在子级中触发ngOnChanges
  • 如果没有看到 plunkr,很难确切地知道什么会起作用。而且我相当有信心有一个比我上面提到的更优雅的解决方案

标签: arrays angular typescript interface


【解决方案1】:

问题在于 Angular 的 ChangeDetection,以及您“更新”父组件上的 Array 属性的方式。

只是将新项目添加到数组中,子组件不会在 OnChanges 生命周期挂钩中注意到。

如果你想解决这个常见问题,在父组件上,做类似这样的事情:

let shortTermData = new ShortTermApplicationAdapter(application);
this.applications.push(shortTermData);
this.applications = [...this.applications]; // Here is the "magic"

最后一行创建了 Array 的新深层副本,并允许 Angular 的 ChangeDetection 注意到 Arrays 的变化。

【讨论】:

    【解决方案2】:

    我是 Angular 的新手,但我总是使用这种语法进行输入

    @Input() applicationsEntry: Array<ApplicationEntryInterface>;
    

    【讨论】:

      【解决方案3】:

      我将 ngOnChanges 与 更改 一起使用。仅当当前值与之前的值不同时,这才会改变,但如果您每次都创建一个对象,它应该可以正常工作。

      changes 会记录组件内每一个被改变的项目。

      试试:

      ngOnChanges(changes: any) {
              if (changes.applicationsEntry) { // this help to filter out undefined
                 console.log(changes.applicationsEntry.currentValue); // your current array should be here
              }
          }
      

      【讨论】:

        猜你喜欢
        • 2020-09-12
        • 2019-09-25
        • 1970-01-01
        • 2019-08-27
        • 2020-04-22
        • 2017-08-12
        • 2018-03-21
        • 2017-12-11
        • 2016-07-20
        相关资源
        最近更新 更多