【问题标题】:angular2 how to iterate array of objectsangular2如何迭代对象数组
【发布时间】:2017-03-31 01:05:53
【问题描述】:

我想迭代一个对象数组,但收到以下错误:

inline template:25:9 caused by: Cannot read property 'length' of null

以下是我的部分代码:

// Definition of the array
public columnsConfig: Array<ColumnConfig>;

其中ColumnConfig 是包含在数组中的所有实例的类。

// Constructor of the component
this.columnsConfig = new Array<ColumnConfig>();


// Function that builds the array to iterate
for(var columnName in _headers) {
  let config = new ColumnConfig(columnName, _headers[columnName]);`
   this.columnsConfig.push(config);`           
}   

模板:

&lt;th *ngFor="let config of columnsConfig"&gt;

我在这里缺少什么?

【问题讨论】:

  • 您发布的内容看起来不错。也许发布更多你的代码。
  • 两件事:-尝试用一个测试 columnsConfig 存在的 ngIf* 来包装你的模板。 - 也许使用 |模板中的异步可能会有所帮助。

标签: arrays angular object


【解决方案1】:

您可以使用 RX js 映射运算符来迭代并创建一个值数组。

import { Component, OnInit } from '@angular/core';
import 'rxjs/add/operator/map';

@Component( {
  selector: 'app-root',
  template:
  `<ol>
    <li *ngFor="let config of columnsConfig ">
    {{config}}
   </li>
   </ol>`
} )
export class AppComponent
{
  ngOnInit() { this.make() }

  public columnsConfig: any[]
  public _headers: any =
  [
    { columnName: 'one', otherName: 'foo' },
    { columnName: 'two', otherName: 'boo' },
    { columnName: 'three', otherName: 'loo' }
  ];

  make()
  {
    let config = [];
    this._headers
      .map( x =>
      {
        config.push( x.columnName );

        this.columnsConfig = config;

        console.log( 'progress: ', config );
      } )
    console.log( 'final result: ', this.columnsConfig );
  }
}

【讨论】:

    【解决方案2】:

    我发现了问题:它与在组成数组的对象中定义的字符串变量的默认值有关。因此,我将默认变量更改为空字符串 ('') 并且它起作用了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-20
      • 1970-01-01
      • 2021-06-22
      • 1970-01-01
      • 2019-08-11
      • 2014-05-06
      相关资源
      最近更新 更多